Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Date() converts certain date strings to local time

Tags:

javascript

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?

like image 609
Kevin S Lin Avatar asked Dec 22 '25 23:12

Kevin S Lin


2 Answers

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());
like image 198
RobG Avatar answered Dec 26 '25 07:12

RobG


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

like image 43
HBP Avatar answered Dec 26 '25 05:12

HBP



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!