3

I'm trying to compare two date strings for equality by wrapping them with the Date() object. I live in Seattle and for some reason, the second date string is converted to PST and then rendered in GMT, resulting in the below:

new Date("January 1, 2012")
>>> Sun Jan 01 2012 00:00:00 GMT-0800 (PST)
new Date("2012-01-01")
>>> Sat Dec 31 2011 16:00:00 GMT-0800 (PST)

Try the above in the chrome console and you should get the same results. How do I get Date to evaluate the second statement as GMT instead of PST?

Kevin S Lin
  • 529
  • 8
  • 14

3 Answers3

4

Do not use the Date object to parse date strings, it is specified as implementation dependent in ECMAScript ed 3 and doesn't work consistently across browsers. One format of ISO8601 date string is specified in ES5, but that doesn't work consistently either. Manually parse the string.

A couple of functions to convert to and from UTC ISO8601 strings:

if (!Date.prototype.toUTCISOString) {

    Date.prototype.toUTCISOString = function() {
      function addZ(n) {
        return (n<10? '0' : '') + n;
      }
      function addZ2(n) {
        return (n<10? '00' : n<100? '0' : '') + n;
      }
      return this.getUTCFullYear() + '-' +
             addZ(this.getUTCMonth() + 1) + '-' +
             addZ(this.getUTCDate()) + 'T' +
             addZ(this.getUTCHours()) + ':' +
             addZ(this.getUTCMinutes()) + ':' +
             addZ(this.getUTCSeconds()) + '.' +
             addZ2(this.getUTCMilliseconds()) + 'Z';
    }
}

if (!Date.parseUTCISOString) {
    Date.parseUTCISOString = function fromUTCISOString(s) {
        var b = s.split(/[-T:\.Z]/i);
        var n= new Date(Date.UTC(b[0],b[1]-1,b[2],b[3],b[4],b[5]));
        return n;
    }
}

var s = '2012-05-21T14:32:12Z'
var d = Date.parseUTCISOString(s);

alert('Original string: ' + s +
      '\nEquivalent local time: ' + d +
      '\nBack to UTC string: ' + d.toUTCISOString());
RobG
  • 142,382
  • 31
  • 172
  • 209
2

Taking robg's advice you might look at DateJS or moment.js

Community
  • 1
  • 1
HBP
  • 15,685
  • 6
  • 28
  • 34
  • is one better than the other? datejs has a long list of outstanding bugs assigned to no one. is moment.js better? – Ray Cheng May 23 '12 at 06:48
  • A single bug in a function you use is a killer. Many bugs in features you do not use do not affect you. Caveat emptor! – HBP May 23 '12 at 07:54
  • Even with a date library, you must tell it the format so it knows how to parse the string. So you must know the format from the beginning, and if you know the format, parsing it manually isn't very hard. – RobG May 23 '12 at 13:25
0

That's because of your time zone, you are 8:00 hours late to the "2012-01-01", so its showing like that, for me i got this

new Date("January 1, 2012")
Sun Jan 01 2012 00:00:00 GMT+0530 (IST)
new Date("2012-01-01")
Sun Jan 01 2012 05:30:00 GMT+0530 (IST)
Ranganadh Paramkusam
  • 4,258
  • 2
  • 22
  • 33