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?
2
Answers
startOfDay
already returns:So there is no need to combine it with
subHours
oraddHours
, just dostartOfDay(d)
:Regarding the time-zone, you’ll need
date-fns-tz
to convert it relative to your current zone / utc, please refer to:Take any passed
Date
object or its parsable string-representation and …Date
instance and assign it to e.g. abegins
constant.begins
date’s values (hours, minutes, milli/seconds) to zero.begins
date.Date
instance from the computed milliseconds and assign it to e.g. anends
constant.