简体   繁体   English

日期-fns | 格式化日期

[英]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:我使用以下调用convertDate函数:

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.我的时区是 CEST。

Error错误

I am getting error:我收到错误: 错误

Expected result:预期结果:

结果

I can call the function by using {convertDate(article.date, "PPP")} which also works.我可以使用同样有效的{convertDate(article.date, "PPP")}来调用该函数。

Please help!请帮忙!

Running the following minimal example at runkit.com returns "2022", it doesn't throw the error described in the OP:runkit.com上运行以下最小示例会返回“2022”,它不会抛出 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:此外,使用new Date是多余的:

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 .正如其他地方所建议的那样,可以使用字符串操作来从时间戳中获取年份,而无需转换为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.如果您需要它作为其他事物的日期(例如格式化的月份名称),请将其转换为日期并重用它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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