'How to convert date from the date fns string format to Date Object

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 ?



Solution 1:[1]

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.

Solution 2:[2]

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}`);

Solution 3:[3]

You can use the moment.js package in function.

For Ref. https://momentjs.com/guides/

According to your code, here is what can be done

import moment from 'moment';

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

const updatedDate = moment(date).format("DD/MM/YYYY")

console.log(updatedDate) // 13/03/2022

With the use of the momentjs package you can convert the date in which ever format required.

Refer this link for more information like format: https://momentjscom.readthedocs.io/en/latest/moment/04-displaying/01-format/

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 KooiInc
Solution 3 Nikhil