开发者

Change time zone by default in JS

PHP has a function called date_default_timezone_set it affects GMT that the Date() command used.

Is there a way that it also affects the JS?

I have this function:

function calcTime(offset) {
    d = new Date();
    utc = d.getTime() + (d.getTimezoneOffset() * 60000);
    nd = new Date(utc + (3600000*offset));
    return nd;
}

Might be called instead to New Date (); problem with her she was good except I开发者_开发百科 want to get New Date(); But if I want to pass on parameters so it's more of a problem ... For example, new Date(year, month);

Does anyone have a solution like in PHP it just affects the New Date(); itself without changing the function be called?


This is an unfortunate question. JavaScript doesn't allow you to set default time zone. And JavaScript doesn't make it easy to subclass Date. You cannot call Date's constructor as function, and if you create a Date with any undefined parameter you get an invalid date.

So, either you create a custom function like you did, or you create a custom date object and define all the functions from Date.

In the interest of forward compatibility and simple code, here is a custom function solution.

(function(){

// Internal timezone settings
var offset_hr = 0;
var offset_ms = 0;

// Get current default timezone in hours
window.getTimezoneOffset = function getTimezoneOffset ( ) { return offset_hr; }

// Set current default timezone in hours
window.setTimezoneOffset = function setTimezoneOffset ( offset ) { 
  offset_hr = offset * 1 ? offset * 1 : 0;
  offset_ms = offset ? offset * 60 * 60 * 1000 : 0;
}

// Create a date with default timezone
window.newDate = function newDate ( year, month, day, hour, min, sec, ms ) {
    // Create base date object
    var d;
    switch ( arguments.length ) {
      case 0 : d = new Date( ); break;
      case 1 : d = new Date( year ); break;
      case 2 : d = new Date( year, month ); break;
      case 3 : d = new Date( year, month, day ); break;
      case 4 : d = new Date( year, month, day, hour ); break;
      case 5 : d = new Date( year, month, day, hour, min ); break;
      case 6 : d = new Date( year, month, day, hour, min, sec ); break;
      case 7 : d = new Date( year, month, day, hour, min, sec, ms ); break;
    }
    // Convert to utc time
    var offset = d.getTimezoneOffset();
    if ( offset || offset_ms ) d.setTime ( d.getTime() + offset * 60 * 1000 + offset_ms );
    return d;
  }
})();

Example usage:

setTimezoneOffset( '+2' );
newDate();
newDate('2011-01-24');
newDate(new Date().getTime());
newDate(2011, 12, 31);
newDate(2011, 12, 31, 12, 34, 56, 789);

As long as you don't check getTimezoneOffset of the new dates, you would do fine.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜