简体   繁体   English

如何使用 date-fns 格式化日期?

[英]How to format date with date-fns?

I've been trying to format a date using date-fns but I keep failing.我一直在尝试使用date-fns格式化日期,但我一直失败。 Basically I have it working just fine with momentJS but not with date-fns:基本上我让它在 momentJS 上工作得很好,但在 date-fns 上却没有:

Here's my date:这是我的约会:

"10-13-20" // month, day, and year

Now with momentJS it works just fine like this:现在使用 momentJS,它可以像这样正常工作:

let result = moment("10-13-20", 'MM-DD-YY').format()
// result = "2020-10-13T00:00:00-06:00"

So I'm trying to do the same using date-fns but no luck.所以我试图使用date-fns做同样的事情,但没有运气。 Can anyone point me in the right direction?任何人都可以指出我正确的方向吗? Thanks in advance!提前致谢!

let result = format(new Date("10-13-20"), 'MM-DD-YY') // Not working

As you can see, with moment lib, we need 2 steps to get the result: parse string to Date object, then format date object to string.如您所见,使用moment lib,我们需要 2 个步骤才能得到结果:将字符串解析为Date对象,然后将 date 对象格式化为字符串。

Your code - format(new Date("10-13-20"), 'MM-DD-YY') is format step, try convert a date object to a string with format template is MM-DD-YY .您的代码 - format(new Date("10-13-20"), 'MM-DD-YY')format步骤,尝试将日期对象转换为格式模板为MM-DD-YY的字符串。 But your date object is not correct.但是您的日期对象不正确。

The solution is doing the same with moment lib:解决方案是用moment lib 做同样的事情:

  1. Parse date string to date object.将日期字符串解析为日期对象。 Use parse使用解析

    const dateString = '10-13-20'; const date = parse(dateString, 'MM-dd-yy', new Date()) // not MM-DD-YY
  2. Format date object to result string.将日期对象格式化为结果字符串。 Use format使用格式

    const result = format(date, "yyyy-MM-dd'T'HH:mm:ss.SSSxxx") console.log(result)

    Result will be like (the same with moment's result in my timezone):结果将类似于(与我的时区中的时刻结果相同):

     2020-10-13T00:00:00.000+09:00
const date = "2021-12-20"
console.log(format(date, "DD-MM-YYYY"));
// output: 20-12-2021

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

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