4

我正在尝试使用 javascript 纪元日期显示本地时间保存记录的时间。问题是纪元日期似乎“卡在”CDT 上。

假设我在 CDT 上午 9:18 保存记录,这作为 js 纪元日期值 1349896693626 进入数据库。我的代码如下:

var savedTime = 1349896693626;
var sDate = new Date();
sDate.setTime(Number(savedTime));
var offset = sDate.getTimezoneOffset();
//grabbing offset and changing it to milliseconds to adjust time
var milliOffset = offset * 60 * 1000;
var adjustedDate = Number(savedTime) - milliOffset;
var displayDate = new Date(adjustedDate);
alert("date is " + displayDate);

我希望 displayDate 显示上午 9:18,如果我在 CDT,它会显示,但如果我移动到 PDT,它会显示上午 5:18,我不明白为什么。就像我必须将偏移量硬编码为 5 小时(CDT 偏移量)才能使其工作,但这没有任何意义。谁能解释发生了什么?

谢谢

4

1 回答 1

0

To display a particular time zone string, ignore the local timezone.

You only care about the GMT time, and the correct offset for the targetted time zone.

Central time is either 6 or 5 hours behind GMT, depending on the range that DST applies.

// standard time offsets
Date.tzones={
    N:['Newfoundland', -210],
    A:['Atlantic', -240],
    E:['Eastern', -300],
    C:['Central', -360],
    M:['Mountain', -420],
    P:['Pacific', -480],
    AK:['Alaska', -540],
    HA_:['Hawaii-Aleutian (Aleutian)', -600],
    HA:['Hawaii-Aleutian (Hawaii)', -600, -1]
};

//find the offset, accurate for US time zones since 2006
Date.dstOff= function(d, tz){
    var off= tz[1], countstart, countend, dstart, dend;
    var y= d.getUTCFullYear();
    if(off  && tz[2]!= -1){
        countstart= 8, countend= 1,
        dstart= new Date(Date.UTC(y, 2, 8, 2)),
        dend= new Date(Date.UTC(y, 10, 1, 2));
        while(dstart.getUTCDay()!== 0) dstart.setUTCDate(++countstart);
        while(dend.getUTCDay()!== 0) dend.setUTCDate(++countend);
        dstart.setUTCMinutes(off);
        dend.setUTCMinutes(off);
        if(dstart<= d && dend>= d) off+= 60;
    }
    return off;
}
//format the result:

Date.short_months= ['Jan', 'Feb', 'Mar', 'Apr',
'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];

Date.toTZString= function(d, tzp){
    d= d? new Date(d):new Date();
    tzp= tzp || 'G';
    var h, m, apm= 'pm', off, dst,
    label= tzp+'ST', str,
    tz= Date.tzones[tzp.toUpperCase()];
    if(!tz) tz= ['Greenwich', 0];
    off= tz[1];
    if(off){
        dst= Date.dstOff(d, tz);
        if(dst!== off) label= tzp+'DT';
        d.setUTCMinutes(d.getUTCMinutes()+dst);
    }
    else label= 'GMT';
    h= d.getUTCHours();
    m= d.getUTCMinutes();
    if(h>12) h-= 12;
    else if(h!== 12) apm= 'am';
    if(h== 0) h= 12;
    if(m<10) m= '0'+m;
    var str= Date.short_months[d.getUTCMonth()]+' '+d.getUTCDate()+', ';
    return str+ h+':'+m+' '+apm+' '+label.toUpperCase();
};

var d= new Date(1349896693626);

alert('Central time: '+Date.toTZString(d,'C'));

returned value: (String) Central time: Oct 10, 2:18 pm CDT

于 2012-10-10T16:40:11.343 回答