It seems that you are using Version 2.0 of date-fns, which is still in alpha (development) status currently.
What functions are available and how they work still seems to change frequently. For example, while in version v2.0.0-alpha.26 toDate() can handle string parameters, it cannot do that any longer in version v2.0.0-alpha.27. There is a new parseISO() function instead.
This should work now:
format(parseISO('2019-02-11T14:00:00'), 'MM/dd/yyyy')
However, while version 2 is still in beta, I would suggest using the stable version 1.x for now.
Answer from NineBerry on Stack OverflowIt seems that you are using Version 2.0 of date-fns, which is still in alpha (development) status currently.
What functions are available and how they work still seems to change frequently. For example, while in version v2.0.0-alpha.26 toDate() can handle string parameters, it cannot do that any longer in version v2.0.0-alpha.27. There is a new parseISO() function instead.
This should work now:
format(parseISO('2019-02-11T14:00:00'), 'MM/dd/yyyy')
However, while version 2 is still in beta, I would suggest using the stable version 1.x for now.
date-fns 2.0.0-alpha.27 (demo: https://stackblitz.com/edit/js-tztuz6)
Use parseISO:
import { format, parseISO } from 'date-fns'
const formattedDate = format(parseISO('2019-02-11T14:00:00'), 'MM/dd/yyyy');
date-fns v1.30.1 (demo: https://stackblitz.com/edit/js-mt3y6p)
Use parse:
import { format, parse } from 'date-fns'
const formattedDate = format(parse('2019-02-11T14:00:00'), 'MM/DD/YYYY');
Hi there,
I have a date string on my DB like this "2022-04-19T08:59:10.177Z". so I'm trying to convert it to something like this "Monday 27th Jan, 2022" using date-fns
So I have a data.json file that has 'createdAt' strings such as ' 1 week ago' , or '2 days ago'. I need to dynamically update this with the current date, so that '1 week ago' becomes '2 weeks ago' a week from now etc. I can't imagine I would have to use a switch statement and hardcode this ('1 week ago') into dates(12-13-25) , there has to be a better way. Thanks
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.
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. But your date object is not correct.
The solution is to do the same as with moment lib:
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-YYFormat 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(parseISO(date), "dd-MM-yyyy"));
// output: 20-12-2021