Home > Blockchain >  date-fns | format date
date-fns | format date

Time:05-29

Problem

I have below function that formats date string.

import { format, parseISO } from "date-fns";

export function convertDate(myDate, displayFormat) {
    return format(new Date(parseISO(myDate)), displayFormat);
}

I have articles that has content such as

title: 'My title'
date: '2022-01-04'

I call the convertDate function using below:

if (articles) {
        for (let i = 0; i < articles.length; i  ) {
            const year = convertDate(articles[i].date, "y");
            years.push(year);
        }
        uniqueYear = [...new Set(years)];
    }

My timezone is CEST.

Error

I am getting error: Error

Expected result:

Result

I can call the function by using {convertDate(article.date, "PPP")} which also works.

Please help!

CodePudding user response:

This is a comment, not an answer because it won't fit in a comment.

Running the following minimal example at runkit.com returns "2022", it doesn't throw the error described in the OP:

var dateFns = require("date-fns")

function convertDate(myDate, displayFormat) {
    return dateFns.format(new Date(dateFns.parseISO(myDate)), displayFormat);
}

let articles = [{
  title: 'My title',
  date: '2022-01-04'
}];

convertDate(articles[0].date, "y"); // "2022"

So the error is elsewhere.

Also, the use of new Date is redundant:

dateFns.format(dateFns.parseISO(myDate), displayFormat)

is sufficient and more robust.

As suggested elsewhere, getting the year from the timestamp can be done using string manipulation, no need for casting to a Date. To get the years:

let articles = [{title: 'title 0', date: '2022-01-04'},
                {title: 'title 1', date: '2020-01-04'}];

let years = articles.map(o => o.date.substring(0,4));

console.log(years);

If you need it as a Date for other things (e.g. formatted month name), cast it to a Date once and reuse it.

  • Related