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

To initialize a JavaScript Date to midnight, you need to set the time components (hours, minutes, seconds, and milliseconds) to zero using the setHours() method.

Syntax

date.setHours(hours, minutes, seconds, milliseconds)

For midnight, use:

date.setHours(0, 0, 0, 0)

Example: Setting Current Date to Midnight

<!DOCTYPE html>
<html>
<body>
   <script>
      var dt = new Date();
      console.log("Original date:", dt.toString());
      
      dt.setHours(0, 0, 0, 0);
      console.log("Midnight date:", dt.toString());
      
      document.write("<p>Original: " + new Date() + "</p>");
      document.write("<p>Midnight: " + dt + "</p>");
   </script>
</body>
</html>
Mon May 28 2018 00:00:00 GMT+0530 (India Standard Time)

Creating a New Date at Midnight

You can also create a new Date object and immediately set it to midnight:

<!DOCTYPE html>
<html>
<body>
   <script>
      // Method 1: Chain the methods
      var midnightDate = new Date().setHours(0, 0, 0, 0);
      
      // Method 2: Create and then set
      var today = new Date();
      today.setHours(0, 0, 0, 0);
      
      document.write("<p>Today at midnight: " + today + "</p>");
   </script>
</body>
</html>

Parameters

Parameter Value for Midnight Description
hours 0 Hour (0-23)
minutes 0 Minutes (0-59)
seconds 0 Seconds (0-59)
milliseconds 0 Milliseconds (0-999)

Common Use Cases

Setting dates to midnight is useful for:

  • Date comparisons (comparing only dates, not times)
  • Creating date ranges that start from the beginning of a day
  • Database queries that need exact date matching
  • Calendar applications

Conclusion

Use setHours(0, 0, 0, 0) to set any JavaScript Date object to midnight. This method modifies the existing date and ensures all time components are reset to zero.

Updated on: 2026-03-15T23:18:59+05:30

571 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements