What is the simplest way to obtain an instance of new Date() but set the time at midnight?
The JavaScript Date is always stored as UTC, and most of the native methods automatically localize the result.
The Date object is created by using new keyword, i.e. new Date(). The Date object can be used date and time in terms of millisecond precision within 100 million days before or after 1/1/1970.
The date. getTime() method is used to return the number of milliseconds since 1 January 1970. when a new Date object is created it stores the date and time data when it is created. When the getTime() method is called on this date object it returns the number of milliseconds since 1 January 1970 (Unix Epoch).
The setHours
method can take optional minutes
, seconds
and ms
arguments, for example:
var d = new Date(); d.setHours(0,0,0,0);
That will set the time to 00:00:00.000
of your current timezone, if you want to work in UTC time, you can use the setUTCHours
method.
Just wanted to clarify that the snippet from accepted answer gives the nearest midnight in the past:
var d = new Date(); d.setHours(0,0,0,0); // last midnight
If you want to get the nearest midnight in future, use the following code:
var d = new Date(); d.setHours(24,0,0,0); // next midnight
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With