Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best way to initialize a JavaScript Date to midnight?

Tags:

javascript

What is the simplest way to obtain an instance of new Date() but set the time at midnight?

like image 871
Sixty4Bit Avatar asked Oct 08 '10 20:10

Sixty4Bit


People also ask

What timezone does JavaScript Date use?

The JavaScript Date is always stored as UTC, and most of the native methods automatically localize the result.

Which is the correct way to create a Date object in JavaScript?

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.

What is new Date () getTime ()?

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


2 Answers

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.

like image 171
Christian C. Salvadó Avatar answered Sep 22 '22 03:09

Christian C. Salvadó


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 
like image 33
Dan Avatar answered Sep 21 '22 03:09

Dan