I have a given date as Date-object in JavaScript.
From that particular date (e.g. 2024-16-01, 22:35), I want to go to the beginning of the day (2024-16-01, 00:00) and the end of the day (2024-16-01, 23:59).
I tried the library date-fns, but this gives wrong values.
import { addDays, addHours, endOfDay, startOfDay, subHours } from 'date-fns';
// d = new Date(...)
const startDate = subHours(startOfDay(d), hoursBefore);
const endDate = addHours(endOfDay(d), hoursAfter);
console.log('Date: ', d);
console.log('Start Of Day: ', startOfDay(d));
console.log('End Of Day: ', endOfDay(d));
console.log('startDate: ', startDate);
console.log('endDate: ', endDate);
Output:
Date: 2024-01-16T17:00:00.000Z
Start Of Day: 2024-01-16T17:00:00.000Z
End Of Day: 2024-01-17T16:59:59.999Z
startDate: 2024-01-16T05:00:00.000Z
endDate: 2024-01-17T21:59:59.999Z
As one can see, the values are totally different from what they actually should be. Is the timezone playing a disturbing role here? If so, how can I mitigate such risks of getting wrong values?
Or is there another approach how to deal with that?
startOfDayalready returns:So there is no need to combine it with
subHoursoraddHours, just dostartOfDay(d):Regarding the time-zone, you'll need
date-fns-tzto convert it relative to your current zone / utc, please refer to: