Search code examples
javascriptnode.jsdatetimeepoch

Convert these time parameters to epoch time


I have the following values;

//date is 14-Dec-2016
let day = 14; 
let month = 12;
let year = 2016;    
let TimezoneOffset = -480; //Timezone is GMT+0800 (Malay Peninsula Standard Time)
let time = 19:34; //in HHMM format

Based on these 5 variables, I would like to get the epoch time in javascript.

I am using node.js v6


Solution

  • You can create a date using the values, apply the timezone offset, then just get the time value:

    var day = 14; 
    var month = 12;
    var year = 2016;    
    var timezoneOffset = -480; //Timezone is GMT+0800 (Malay Peninsula Standard Time)
    var time = '19:34'; //in HHMM format
    
    // Create date using UTC methods but local values
    var date = new Date(Date.UTC(year, month - 1, day, time.split(':')[0], time.split(':')[1]));
    
    // Apply timezone offset to set to UTC time
    date.setMinutes(date.getMinutes() + timezoneOffset);
    var timeValue = date.getTime();
    
    // milliseconds since 1970-01-01T00:00:00Z
    console.log(timeValue);
    
    // Check UTC date and time value
    console.log(new Date(timeValue).toUTCString());

    Note that variables starting with a capital letter are, by convention, reserved for constructors. And a time like "19:34" must be a string, not a number.