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
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
Share
Improve this question
asked Aug 16, 2021 at 18:59
Asit PrakashAsit Prakash
3614 silver badges9 bronze badges
4
-
1
Wele to timezones :)
new Date("2021-08-15T18:30:00.000Z")
should transform it back to your timezone – dbuchet Commented Aug 16, 2021 at 19:01 - @dbuchet I knew this is related to timezones. God, I hate dates. Can you give some references to how can I modify parse with tz. Thanks, man :) – Asit Prakash Commented Aug 16, 2021 at 19:04
- 2 Its is giving you the UTC time, convert it to your local time and you will good to go – Nisharg Shah Commented Aug 16, 2021 at 19:19
-
1
You have
date-fns-tz
if you need to deal with timezones. And good luck :) – dbuchet Commented Aug 16, 2021 at 22:29
5 Answers
Reset to default 9We 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
I was using in a filter so the initial value was with "-" and i have to replace it for using "/" as well, it work's like a charm
filters: { formatedDate(value) { value = value.replaceAll('-', '/') return format(new Date(value), 'd MMM') } },
and append it in html with a pipe like this
{{ date | formatedDate }}
so the output on the screen was
for a string '2022-10-21'
None of the solutions worked for me, because the timezone was still not being unconsidered. Instead, I used:
import { isValid } from 'date-fns'
let removeTimezone = (date) => {
date = new Date(date);
return new Date(
date.valueOf() + date.getTimezoneOffset() * 60 * 1000
);
};
const date = '2023-01-22'
const dtDateOnly = removeTimezone(date)
if(!isValid(dtDateOnly)) console.log("cannot convert to date")
else console.log(dtDateOnly)
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"