Search code examples
javascriptdatetimeunix-timestampgmt

How to convert GMT date time into GMT Unix TimeStamp using JS?


I know there are various ways using which we can convert date time into Unix timestamp.

But the problem is when we convert GMT's Date time value into Unix timestamp then it shows the value of timestamp according to my local timezone's value i.e. Asia/Kolkata

For example: Date time of GMT is: 2018-08-21 11:37:56 So when I am converting it into Unix timestamp then it returns as follows:

var t = new Date('2018-08-21 11:37:56').getTime() / 1000;
console.log(t); // 1534831676

I am looking for 1534851476 which is a value according to the GMT time zone.

which is Unix timestamp according to my local time zone Asia/Kolkata. Can anyone help me out to get Unix timestamp value into GMT?

For more information: you can check the Unix timestamp value of GMT date time here on this link.

Thank you!


Solution

  • Without a timezone, new Date assumes localtime

    so, lets say you retrieve the string

    var date = '2018-08-21 11:37:56';
    

    what you can do is

    var date = '2018-08-21 11:37:56';
    var t = new Date(date.replace(' ', 'T') + 'Z').getTime() / 1000;
    console.log(t); // 1534851476 - see for yourself