Search code examples
javascriptdatetimestamp-with-timezone

Parse date without timezone javascript


I want to parse a date without a timezone in JavaScript. I tried:

new Date(Date.parse("2005-07-08T00:00:00+0000"));

Which returned Fri Jul 08 2005 02:00:00 GMT+0200 (Central European Daylight Time):

new Date(Date.parse("2005-07-08 00:00:00 GMT+0000"));

returns the same result and:

new Date(Date.parse("2005-07-08 00:00:00 GMT-0000"));

also returns the same result.

I want to parse time:

  1. without time zone.
  2. without calling a constructor Date.UTC or new Date(year, month, day).
  3. by simply passing a string into the Date constructor (without prototype approaches).

I have to produce a Date object, not a String.


Solution

  • The date is parsed correctly, it's just toString that displays the timestamp in your local timezone:

    let s = "2005-07-08T11:22:33+0000";
    let d = new Date(Date.parse(s));
    
    // this logs for me 
    // "Fri Jul 08 2005 13:22:33 GMT+0200 (Central European Summer Time)" 
    // and something else for you
    
    console.log(d.toString()) 
    
    // this logs
    // Fri, 08 Jul 2005 11:22:33 GMT
    // for everyone
    
    console.log(d.toUTCString())

    Javascript Date object are time values - they merely contain a number of milliseconds since the epoch. There is no timezone info in a Date object. Which calendar date (day, minutes, seconds) this timestamp represents is a matter of the interpretation (one of to...String methods).

    The above example shows that the date is being parsed correctly for offset +0000 - that is, it actually contains an amount of milliseconds corresponding to "2005-07-08T11:22:33" in GMT.