I have a date object which is when I did stringify
const date = "2022-03-13T18:30:00.00Z"
Now I am trying to convert this in a format using date-fns
format(date, "dd MMM yyyy")
this returns the string
and not the date object which will be as of the date string.
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. You cannot get it to return a Date
object because Date
objects are not just a way to format a string. You can read about format
in the date-fns documentation .
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:
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. 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.
Of course you do not need to use const
, I am simply following what you have.
I would recommend reading about Date
objects. the Tutorialspoint page is a good place to start.
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
.
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}`);
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.