简体   繁体   English

如何将日期从日期 fns 字符串格式转换为日期 Object

[英]How to convert date from the date fns string format to Date Object

I have a date object which is when I did stringify我有一个日期 object,这是我进行字符串化的时间

   const date =  "2022-03-13T18:30:00.00Z"

Now I am trying to convert this in a format using date-fns现在我正在尝试使用 date-fns 将其转换为格式

format(date, "dd MMM yyyy")

this returns the string and not the date object which will be as of the date string.这将返回string而不是日期 object,它将作为日期字符串。

I tried with我试过

format(parseISO(date), "dd MMM YYYY")

Still it does not work.仍然不起作用。

Can any one help me with this?谁能帮我这个?

format is a function that always returns a string. format是一个 function,它总是返回一个字符串。 You cannot get it to return a Date object because Date objects are not just a way to format a string.您不能让它返回Date object,因为Date对象不仅仅是格式化字符串的一种方式。 You can read about format in the date-fns documentation .您可以在date-fns 文档中阅读有关format的信息。
If you want to use a string to get a date object, you can simply use the constructor for the Date class. Here are some acceptable ways to instantiate a Date object:如果要使用字符串获取date object,只需使用Date Date的一些可接受的方法:

new Date( )
new Date(milliseconds)
new Date(datestring)
new Date(year,month,date[,hour,minute,second,millisecond ])

For your case we will use new Date(dateString) as you already have that.对于您的情况,我们将使用您已有的new Date(dateString) So you can simply do this:所以你可以简单地这样做:

const date =  "2022-03-13T18:30:00.00Z";
const dateObject = new Date(date);

And then you will have a Date object with all of the convenient methods that come with it.然后您将拥有一个Date object 以及它附带的所有方便方法。
Of course you do not need to use const , I am simply following what you have.当然你不需要使用const ,我只是按照你所拥有的。
I would recommend reading about Date objects.我建议阅读有关Date对象的信息。 the Tutorialspoint page is a good place to start. Tutorialspoint 页面是一个很好的起点。

The datestring you show ( "2022-03-13T18:30:00.00Z" ) is simply convertable to a Date object. Now, to format that back to a date string you wish, try using Intl.DateTimeFormat .您显示的日期字符串 ( "2022-03-13T18:30:00.00Z" ) 可以简单地转换为Date object。现在,要将其格式化回您想要的日期字符串,请尝试使用Intl.DateTimeFormat

 const date = new Date("2022-03-13T18:30:00.00Z"); const formatOptions = { year: 'numeric', month: 'long', day: '2-digit' }; const [MMM, dd, yyyy] = new Intl.DateTimeFormat(`en-EN`, formatOptions).formatToParts(date).filter( v => v.type.== `literal`).map( v => v;value ). console;log(`${dd} ${MMM} ${yyyy}`);

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

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