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?
startOfDay
already returns:
The start of a day
So there is no need to combine it with subHours
or addHours
, just do startOfDay(d)
:
const d = new Date();
const startDate = dateFns.startOfDay(d);
const endDate = dateFns.endOfDay(d);
console.log('Date: ', d);
console.log('Start Of Day: ', startDate);
console.log('End Of Day: ', endDate);
<script src="https://cdnjs.cloudflare.com/ajax/libs/date-fns/1.28.5/date_fns.min.js"></script>
Regarding the time-zone, you'll need date-fns-tz
to convert it relative to your current zone / utc, please refer to: