How to Initialize a JavaScript Date to Midnight?
JavaScript can be used to initialize a JavaScript Date to midnight i.e. set hours like (0,0,0,0). In many applications, there is a need to work with dates set to midnight, meaning the start of the day at 00:00:00.000 hours such as When performing date calculations, we often need to start from the beginning of the day.
Below are the approaches to initialize a JavaScript date to midnight:
Table of Content
- Using setHours Methods
- Using UTC Methods
Using setHours Methods
Create a new Date object to get the current date and time. Use the setHours method to set the time to midnight (00:00:00.000). Now, access the various components of the date (year, month, day, hour, minute, second, millisecond) to ensure that the time has been set correctly.
Example: To demonstrate initialization a JavaScript Date to midnight using setHours Methods
// Create a new Date object to
// get the current date and time
const date = new Date();
// Set the time to midnight (00:00:00.000)
date
.setHours(0, 0, 0, 0);
// Access the other components of the date
// to verify the time is set to midnight
const year = date
.getFullYear();
const month = date
.getMonth() + 1;
const day = date
.getDate();
const hour = date
.getHours();
const minute = date
.getMinutes();
const second = date
.getSeconds();
const millisecond = date
.getMilliseconds();
console.log(`Date: ${year}-${month}-${day}`);
console.log(`Time: ${hour}:${minute}:${second}.${millisecond}`);
Output
Date: 2024-5-24 Time: 0:0:0.0
Time Complexity: O(1)
Space Complexity: O(1)
Using UTC Methods
Use the Date.UTC method to create a Date object set to a specific date at midnight in UTC. Retrieve the year, month, day, hour, minute, second, and millisecond to ensure the time has been set correctly.
Example: To demonstrate initialization a JavaScript Date to midnight using UTC Methods
// Create a Date object for May
// 24, 2024, at midnight UTC
const date = new Date(Date.UTC(2024, 4, 24));
// Access the various components of the date
// to verify the time is set to midnight UTC
const yearUTC = date
.getUTCFullYear();
const monthUTC = date
.getUTCMonth() + 1; // Months are zero-indexed
const dayUTC = date
.getUTCDate();
const hourUTC = date
.getUTCHours();
const minuteUTC = date
.getUTCMinutes();
const secondUTC = date
.getUTCSeconds();
const millisecondUTC = date
.getUTCMilliseconds();
// Log the components to verify the time is set to midnight UTC
console.log(`UTC Date: ${yearUTC}-${monthUTC}-${dayUTC}`);
console.log(`UTC Time: ${hourUTC}:${minuteUTC}:${secondUTC}.${millisecondUTC}`);
Output
UTC Date: 2024-5-24 UTC Time: 0:0:0.0
Time Complexity: O(1)
Space Complexity: O(1)