Search code examples
javascriptdatedatetimeisogmt

Javascript: Can you convert your local time to GMT like so, new Date(localTime + 'GMT')?


I currently have a var dateNow as '10 1 2016' and var timeNow as '05:15:50' and was able to convert to UTC like so var dateTimeNow = Date(dateNow + timeNow + ' UTC');

Would now like to convert it to GMT, so is it as simple as just changing ' UTC' to ' GMT'? So like, var dateTimeNow = Date(dateNow + timeNow + ' GMT');?


Solution

  • If you have a date like "10 1 2016" (Which I guess is 10 January, 2016) and a time like "05:15:50" then you can create a date for that time in a timezone with a zero offset as an ISO 8601 formatted string: "2016-01-10T15:15:50Z" or "2016-01-10T15:15:50+0000".

    An ISO 8601 extended format string should be parsed correctly in modern implementations, however in general it's not a good idea to parse strings with the Date constructor (or Date.parse, they are equivalent for parsing) due to variances in implementations. If you have a single format, it can be parsed in a couple of lines. Alternatively, use one of the many Date libraries that have a parser and formatter and remember to always give the parser the format of the string you wish it to parse.

    As for converting a local time to UTC, you must know the time zone offset of the local time, otherwise you have no datum to adjust it.

    To "convert" a local date like 10 January, 2016 at 05:15:50 to UTC (where "local" is whatever the host system time zone is set to) is a simple as:

    var d = new Date(2016,0,10,5,15,50);
    console.log('Local: ' + d.toLocaleString() +
                '\nUTC: ' + d.toISOString()); 

    Note that toLocaleString is entirely implementation dependent, often ignores browser and system settings and produces a different result in different implementations.

    This allows the host to consider the current system time zone settings and apply them when creating the date. ECMAScript Date objects have a time value that is based on UTC, so they are inherently UTC.