How to Initialize a JavaScript Date to Midnight?
Last Updated :
21 Aug, 2024
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:
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
JavaScript
// 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}`);
OutputDate: 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
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}`);
OutputUTC Date: 2024-5-24
UTC Time: 0:0:0.0
Time Complexity: O(1)
Space Complexity: O(1)
Using setUTCHours Method
The setUTCHours method in JavaScript allows you to set the hour, minute, second, and millisecond for a date object in Coordinated Universal Time (UTC). This approach is particularly useful when working with dates across different time zones or when you want to ensure consistency by using UTC.
Example:
JavaScript
// Create a new Date object with the current date and time
let currentDate = new Date();
currentDate.setUTCHours(0, 0, 0, 0);
console.log("Year: " + currentDate.getUTCFullYear());
console.log("Month: " + (currentDate.getUTCMonth() + 1)); // Months are zero-based
console.log("Day: " + currentDate.getUTCDate());
console.log("Hours: " + currentDate.getUTCHours());
console.log("Minutes: " + currentDate.getUTCMinutes());
console.log("Seconds: " + currentDate.getUTCSeconds());
console.log("Milliseconds: " + currentDate.getUTCMilliseconds());
OutputYear: 2024
Month: 8
Day: 21
Hours: 0
Minutes: 0
Seconds: 0
Milliseconds: 0
Using toISOString Method
The toISOString method can be used to generate a standardized string representing the date in ISO 8601 format (YYYY-MM-DDTHH:mm
.sssZ). The string will always represent midnight in UTC if the hours, minutes, seconds, and milliseconds are set to zero. After generating the ISO string, you can convert it back to a Date object if needed.
Example: Initialize a JavaScript Date to Midnight Using toISOString Method
JavaScript
// Create a new Date object for the current date
let currentDate = new Date();
// Set the time to midnight in UTC using the toISOString method
let midnightISO = currentDate.toISOString().split('T')[0] + 'T00:00:00.000Z';
// Convert the ISO string back to a Date object
let midnightDate = new Date(midnightISO);
// Access the components to verify the time is set to midnight UTC
console.log("ISO String: " + midnightISO);
console.log("Year: " + midnightDate.getUTCFullYear());
console.log("Month: " + (midnightDate.getUTCMonth() + 1)); // Months are zero-based
console.log("Day: " + midnightDate.getUTCDate());
console.log("Hours: " + midnightDate.getUTCHours());
console.log("Minutes: " + midnightDate.getUTCMinutes());
console.log("Seconds: " + midnightDate.getUTCSeconds());
console.log("Milliseconds: " + midnightDate.getUTCMilliseconds());
OutputISO String: 2024-08-21T00:00:00.000Z
Year: 2024
Month: 8
Day: 21
Hours: 0
Minutes: 0
Seconds: 0
Milliseconds: 0
Similar Reads
How to Add Days to Date in JavaScript?
Adding days to a date in JavaScript is a common task when working with dates and times. This involves manipulating the Date object to calculate a future or past date by adding a specific number of days. This is useful for tasks like scheduling events, and deadlines, or simply adjusting dates dynamic
2 min read
How to calculate minutes between two dates in JavaScript ?
Given two dates and the task is to get the number of minutes between them using JavaScript. Approach: Initialize both Date object.Subtract the older date from the new date. It will give the number of milliseconds from 1 January 1970.Convert milliseconds to minutes. Example 1: This example uses the c
2 min read
How to Log the Current Date in JavaScript ?
The Date object is an inbuilt object constructor of JavaScript language. It is used to work with dates and times. The Date object is created by using the new keyword, i.e. new Date(). The current date can be logged on the console in JavaScript using the below-discussed methods. Table of Content Usin
3 min read
How to Convert Date to Another Timezone in JavaScript?
Converting a date to another timezone in JavaScript means adjusting the local date and time to match the time in a different timezone. This ensures that the displayed time aligns with the selected timezone, often using built-in methods or external libraries. 1. Using Intl.DateTimeFormat() and format
2 min read
How to get tomorrow's date in a string format in JavaScript ?
In this article, we will see how to print tomorrow's date in string representation using JavaScript. To achieve this, we use the Date object and create an instance of it. After that by using the setDate() method, we increase one date to the present date. Now by using the getDate() method you will ge
2 min read
How to convert a JavaScript date to UTC?
Javascript date can be converted to UTC by using functions present in the Javascript Date object. The toUTCString() method is used to convert a Date object into a string, according to universal time. The toGMTString() returns a string that represents the Date based on the GMT (UT) time zone. By defa
1 min read
How to get JavaScript Date in UTC using MomentJS?
When working with dates and times in JavaScript, especially in applications that deal with users across different time zones, it is often necessary to work with dates in UTC (Coordinated Universal Time). Below are the approaches to get a date in UTC using Moment.js: Table of Content Using moment().u
2 min read
How to get the current date in JavaScript ?
The Date() object is used to access the current date in JavaScript. To get the current date in string format, we can use toDateString() method. The date.toDateString() method converts the given date object into the date portion into a string. Syntax dateObj.toDateString()[GFGTABS] JavaScript // Crea
2 min read
How to get Month and Date of JavaScript in two digit format ?
To get the Month and Date of JavaScript in two-digit format, we have multiple approaches. In this article, we are going to learn how to get the Month and Date of JavaScript in a two-digit format. Below are the approaches used to get the Month and Date of JavaScript in two-digit format: Table of Cont
3 min read
How to calculate the yesterday's date in JavaScript ?
In this article, we will see how to calculate yesterdayâs date in JavaScript. To calculate yesterday's date, you need to have some basic ideas of a few methods of JavaScript. JavaScript getDate() MethodJavaScript setDate() MethodJavaScript getDate() Method: It is an inbuilt JavaScript function that
3 min read