Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript Date.toJSON don't get the timezone offset

Well the problem is that I was using code like this:

new Date().toJSON().slice(0, 10)

to get my date as YYYY-MM-DD string, then I use it like parameter in some mysql queries and in some condition statements. In the end of the day I wasn't getting the right date since it was still in the previous day (my timezone offset is +2/3 hours).

I haven't noticed that the toJSON method does not take into account your timezone offset, so I've ended up with this hacky solution:

var today = new Date();
today.setHours( today.getHours()+(today.getTimezoneOffset()/-60) );
console.log(today.toJSON().slice(0, 10));

Is there a more elegant solution?

  • Here is the test code: http://jsfiddle.net/simo/qwhYw/
  • JavaScript toJSON Method
  • JavaScript Date Object
like image 687
simo Avatar asked Jul 08 '12 11:07

simo


1 Answers

Date objects in ECMAScript are internally UTC. The timezone offset is used for local times.

The specification for Date.prototype.toJSON says that it uses Date.prototype.toISOString, which states that "the timezone is always UTC". What your solution is doing is offsetting the UTC time value of the date object by the timezone offset.

Consider adding your own method to Date.prototype, e.g.

Date.prototype.toJSONLocal = function() {
  function addZ(n) {
    return (n<10? '0' : '') + n;
  }
  return this.getFullYear() + '-' + 
         addZ(this.getMonth() + 1) + '-' + 
         addZ(this.getDate());
} 

Edit

If you want to squeeze extra performance, the following should be faster:

Date.prototype.toJSONLocal = (function() {
    function addZ(n) {
        return (n<10? '0' : '') + n;
    }
    return function() {
      return this.getFullYear() + '-' +
             addZ(this.getMonth() + 1) + '-' +
             addZ(this.getDate());
    };
}())

But that smacks of premature optimisation, so unless you are calling it thousands of times in a very short period, I wouldn't bother.

like image 92
RobG Avatar answered Oct 09 '22 18:10

RobG