How to get current date/time in seconds in JavaScript?

To get the current time in seconds in JavaScript, you can extract hours, minutes, and seconds from a Date object and convert them to total seconds using the formula:

(hours * 3600) + (minutes * 60) + seconds

Method 1: Converting Current Time to Seconds

This approach gets individual time components and calculates total seconds since midnight:

<html>
   <head>
      <title>JavaScript Get Seconds</title>
   </head>
   <body>
      <script>
         var dt = new Date();
         var sec = dt.getSeconds();
         document.write("Seconds: " + sec);
         var min = dt.getMinutes();
         document.write("<br>Minutes: " + min);
         var hrs = dt.getHours();
         document.write("<br>Hours: " + hrs);
         var total_seconds = (hrs*3600) + (min*60) + sec;
         document.write("<br>Total seconds since midnight: " + total_seconds);
      </script>
   </body>
</html>
Seconds: 35
Minutes: 37
Hours: 9
Total seconds since midnight: 34655

Method 2: Using getTime() for Unix Timestamp

For getting seconds since January 1, 1970 (Unix timestamp), use getTime() and divide by 1000:

<html>
   <head>
      <title>Unix Timestamp in Seconds</title>
   </head>
   <body>
      <script>
         var now = new Date();
         var unixTimestamp = Math.floor(now.getTime() / 1000);
         document.write("Current Unix timestamp: " + unixTimestamp);
         document.write("<br>Readable date: " + now.toString());
      </script>
   </body>
</html>
Current Unix timestamp: 1703847455
Readable date: Fri Dec 29 2023 09:37:35 GMT+0000 (UTC)

Method 3: Using Date.now() (Shorter Approach)

Date.now() returns milliseconds since Unix epoch. Divide by 1000 for seconds:

<html>
   <head>
      <title>Date.now() in Seconds</title>
   </head>
   <body>
      <script>
         var secondsSinceEpoch = Math.floor(Date.now() / 1000);
         document.write("Seconds since Jan 1, 1970: " + secondsSinceEpoch);
      </script>
   </body>
</html>
Seconds since Jan 1, 1970: 1703847455

Comparison

Method Returns Use Case
Time components formula Seconds since midnight Daily time calculations
getTime() / 1000 Unix timestamp Database storage, APIs
Date.now() / 1000 Unix timestamp Quick timestamp generation

Conclusion

Use the time components method for seconds since midnight, or Date.now() / 1000 for Unix timestamps. Choose based on whether you need daily time or absolute timestamp.

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

769 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements