Given a date, we can calculate the number of seconds that have elapsed since the Unix epoch, which is January 1, 1970, 00:00:00 UTC. JavaScript's getTime() method returns the time in milliseconds since the epoch. By dividing this value by 1000 and using Math.floor(), we can obtain the number of seconds since the epoch.
These are the following approaches to get seconds since epoch in JavaScript:
Approach 1: Using getTime() Method
In this approach, we use the getTime() method to get the number of milliseconds since the epoch and divide it by 1000 to convert milliseconds into seconds. Math.floor() is used to return the integer value.
Syntax:
date.getTime()Example: In this example, we calculate the number of seconds since the epoch for a given date.
<script type="text/javascript">
function seconds_since_epoch(d) {
return Math.floor(d.getTime() / 1000);
}
// Create a date
var d = new Date(2020, 4, 29, 22, 0, 0, 0);
// Get seconds since epoch
var sec = seconds_since_epoch(d);
document.write("Date " + d + " has "
+ sec + " seconds since epoch.");
</script>
Output:
Date Fri May 29 2020 22:00:00 GMT+0530 (India Standard Time) has 1590769800 seconds since epoch.Approach 2: Using Date.now()
The Date.now() method returns the current time in milliseconds since the Unix epoch. Dividing it by 1000 and using Math.floor() gives the current number of seconds since the epoch.
Example: In this example, we get the current number of seconds since the epoch.
<script type="text/javascript">
let seconds = Math.floor(Date.now() / 1000);
document.write("Seconds since epoch: " + seconds);
</script>
Output:
Seconds since epoch: 178774...Note: The output of Date.now() changes depending on the current date and time.