Here are 2 ready-to-use functions to get the first and last millisecond of a day using a few lines of vanilla JavaScript.
Get the first moment of a day
/**
* Get first millisecond of a date
* @param {Date} dateObj - JS Date object, default is current time
* @returns date object with time set to first millisecond of the day
*/
const beginningOfDay = function beginningOfDay (dateObj) {
//Get current date
const now = dateObj || new Date();
const year = now.getFullYear();
const month = now.getMonth();
const day = now.getDate();
return new Date(year, month, day);
};
1. Set a default value to the date argument
In case of no argument we set the date to current date and time. The below basically means if dateObj
is defined set now
to that, otherwise set it to a new Date
object.
const now = dateObj || new Date();
2. Extract the date data
new Date()
returns the current date and time. Similarly, any Date
object you input as an argument will probably also have a time. To get the start of a day we will need a fresh start. For that we first extract the year, month and day.
const now = dateObj || new Date();
const year = now.getFullYear();
const month = now.getMonth();
const day = now.getDate();
3. We generate and return a "fresh" date
By generating a new Date
using year
, month
and day
as arguments you set the date of the JavaScript Date
object. Because you didn't set the time, JS will set it to the first value which is 0 (0 hours, 0 minutes, 0 seconds, 0 milliseconds) .
return new Date(year, month, day);
Get the last moment of a day
/**
* Get last millisecond of a date
* @param {Date} dateObj - JS Date object, default is current time
* @returns date object with time set to last millisecond of the day
*/
const lastMomentOfDay = function lastMomentOfDay(dateObj) {
//Tomorrow = Current day + 1
let tomorrow = beginningOfDay(dateObj);
tomorrow.setDate(tomorrow.getDate() + 1);
//Tommorow - 1 milisecond = result
let result = new Date();
result.setTime(tomorrow.getTime() - 1);
return result;
};
1. Get the first moment of the next day
We leverage the function we wrote above (have a 🍪 for keeping your code DRY).
let tomorrow = beginningOfDay(dateObj);
tomorrow.setDate(tomorrow.getDate() + 1);
2. Subtract a millisecond from tomorrow
Remember, we got the first moment of tomorrow. If we subtract a millisecond from that, we will get the last millisecond the the day before, which is exactly what we are looking for.