How to use UTC Methods In Javascript

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

JavaScript
// 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)



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

Similar Reads

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....

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....