Categories
JavaScript Answers

How to Initialize a JavaScript Date to Midnight?

Spread the love

Sometimes, we may want to set a JavaScript date to midnight.

In this article, we’ll look at how to initialize a JavaScript date to midnight.

Date.prototype.setHours

We can use the setHours method to set the hour of the date to midnight.

For instance, we can write:

const d = new Date();  
d.setHours(0, 0, 0, 0);  
console.log(d)

We call setHours with the hours, minutes, seconds, and milliseconds all set to 0 to set the date d to midnight of the same date as the original date d .

The change mutates the d object.

So we see that d is midnight of the current date from the console log.

To set a date to tomorrow’s midnight, we can write:

const d = new Date();  
d.setHours(24, 0, 0, 0);  
console.log(d)

The first argument, which is the hours argument, is 24 instead of 0.

And from the console log, we should see that the date is the next day midnight.

If we want to make a copy of the date, we can pas the date to the Date constructor:

const d = new Date(new Date().setHours(0, 0, 0, 0));  
console.log(d)

Date.prototype.setUTCHours

If we want to work with UTC times, we can use the setUTCHours method to set a time to midnight.

For instance, we can write:

const d = new Date();  
d.setUTCHours(0, 0, 0, 0);  
console.log(d)

to set a date to midnight UTC.

moment.js

The moment.js library lets us set a date to midnight with the startOf method.

For instance, we can write:

const d = moment().startOf('day');  
console.log(d)

We call startOf with 'day' to set the moment object’s date-time to midnight of the same date that the moment date is on.

Conclusion

We can set a JavaScript date to midnight with native JavaScript date methods.

Also, we can use moment.js to do the same thing.

Leave a Reply

Your email address will not be published. Required fields are marked *