qweeee
qweeee

Reputation: 63

Get invalid date when use date-fns

I was using date-fns library and have the following code:

 isSameMonth(parse('17. 3. 2021 17:44', 'yyyy-MM-dd', new Date()), new Date())

but it returns false which is wrong. But to test it out more I tried executing

console.log(parse('17. 3. 2021 17:44', 'yyyy-MM-dd', new Date()))

and it returns "Invalid date"

No idea why

Upvotes: 1

Views: 7031

Answers (2)

Quentin
Quentin

Reputation: 944205

The date you are parsing has to match the date format you say you are parsing.

'17. 3. 2021 17:44' isn't remotely like 'yyyy-MM-dd'

This works when I test it in Node.js (but I can't persuade it to work in the browser with date-fns hosted on a CDN):

console.log(parse('17. 3. 2021 17:44', 'd. M. yyyy HH:mm', new Date()));

Do read the the documentation.

Upvotes: 0

Kevin Le - Khnle
Kevin Le - Khnle

Reputation: 10877

You would need the following:

console.log(parse('17. 3. 2021 17:44', 'dd. MM. yyyy HH:mm', new Date()))

and

const sameMonth = isSameMonth(parse('17. 3. 2021 17:44', 'dd. MM. yyyy HH:mm', new Date()), new Date())
console.log(sameMonth)

Upvotes: 0

Related Questions