Open In App

How to get seconds since epoch in JavaScript?

Last Updated : 14 May, 2020
Improve
Improve
Like Article
Like
Save
Share
Report

Given a date, we have to find the number of seconds since the epoch (i.e. 1 January 1970, 00:00:00 UTC ). The getTime() method in the JavaScript returns the number of milliseconds since January 1, 1970, or epoch. If we divide these milliseconds by 1000 and then integer part will give us the number of seconds since epoch.

Example:

Input: Date = 27-04-2020, 11:55:55
Output: Seconds since epoch - 1587968755

Syntax:

new Date(year, month, day, hours, minutes, seconds, milliseconds)

Example:




<script type="text/javascript">
    function seconds_since_epoch(d){ 
        return Math.floor( d / 1000 ); 
    }
      
    // Driver Code
    var d = new Date(2020, 4, 29, 22, 00, 00, 00);
    var sec = seconds_since_epoch(d);
    document.write("Date " + d + " has " 
                   + sec+ " seconds till epoch.");
</script>                    


Output:

Date Fri May 29 2020 22:00:00 GMT+0530 (India Standard Time) 
has 1590769800 seconds till epoch.

Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads