Search code examples
javascriptgoogle-mapsdate-conversion

Calculate new Date() as seconds since midnight, January 1, 1970 UTC


I am attempting to use the Google Maps timezone API to get the datetime for a specific location (e.g. New York).

According to the API documentation:

Required Parameters:

timestamp specifies the desired time as seconds since midnight, January 1, 1970 UTC.

The issue I am having is calculating the difference in seconds from two Date() objects:

let currentDate = new Date();                   // local user time 
let epochDate = new Date('January 1, 1970');    // epoch date

// calculate seconds since (currentDate - epochDate)

Solution

  • Use the getTime() function on a Date instance:

    let secondsSinceEpoch = new Date().getTime() / 1000;
    

    No need to set Epoch (January 1, 1970), all dates are relative to that date.