Reputation: 34023
I'm trying out date-fns v2.
I want to format a date in a string by using the toDate
and format
functions:
import { format, toDate } from 'date-fns'
format(toDate('2019-02-11T14:00:00'), 'MM/dd/yyyy')
But get the following error:
RangeError: Invalid time value
Upvotes: 28
Views: 118883
Reputation: 868
In date-fns version 3.6.0, you can reliably format a date string using the toDate function.
import { format, toDate } from 'date-fns'
format(toDate('2019-02-11T14:00:00'), 'MM/dd/yyyy')
console.log(dateFns.format(dateFns.toDate('2019-02-11T14:00:00'), 'MM/dd/yyyy'))
<script src="https://cdn.jsdelivr.net/npm/[email protected]/cdn.min.js"></script>
Upvotes: 0
Reputation: 1044
Btw, one more case to validate:
import { isValid, parseISO, parse } from 'date-fns'
// Date valid
if (isValid(parseISO('2019-11-27 09:45:00'))) {
let dt = parse('2019-11-27 09:45:00', 'yyyy-MM-dd HH:mm:ss', new Date())
}
Upvotes: 12
Reputation: 5293
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');
Upvotes: 17
Reputation: 28499
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.
Upvotes: 38
Reputation: 27
The method toDate is not able to read that format.
Try to convert to Date lke this:
var date = new Date('2019-02-11T14:00:00')
Upvotes: 0