parse function in date-fns returns one day previous value

Viewed 2397

I am trying to parse date using date-fns library but getting one day previous as result. How can I avoid this and get the right result?

start = '2021-08-16'
const parseStart = parse(start, 'yyyy-MM-dd', new Date());

output:

2021-08-15T18:30:00.000Z
3 Answers

We had a similar problem while trying to use the date-fns format function on a hyphened string date. It was subtracting one day from the date while formating. The solution was in fact to change the hypes for slashes.

const dateString = '2010-08-03'
const date = new Date(dateString.replace(/-/g, '/'))

Not to have this timezone overhead I'd suggest formatting your date string into ISO string and then using parseISO function of date-fns.

Like this:

import { parseISO } from 'date-fns';

const parseStringDate = (dateString: string): Date => {
  const ISODate = new Date(dateString).toISOString();
  return parseISO(ISODate);
};

parseStringDate("2021-08-19") //2021-08-19T00:00:00.000Z

This worked for me (v.2+):

// wrong:
const date = format(new Date('2021-10-01'),'dd/MM/yyyy')
console.log(date) // "30/09/2021"

// ok:
const date = format(new Date('2021/10/01'),'dd/MM/yyyy')
console.log(date) // "01/10/2021"
Related