简体   繁体   中英

date-fns | format date

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: 错误

Expected result:

结果

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

Please help!

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 (eg formatted month name), cast it to a Date once and reuse it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM