ET中的当前日期/时间

时间:2012-03-12 14:48:41

标签: javascript date timezone dst

是否有一种简单(或其他方面很好)的方式来获取东部时间的当前日期和时间,以便在当前和目标时区中节省可能的夏令时? (我认为,America/New_York是使用tz的人的真正目标。)

当然,主要的困难是找出纽约(EST或EDT)当前时区的用途。 Javascript可以这样做吗?还是有好的图书馆吗?我对计算的硬编码很谨慎,因为我的代码在新法律通过时会过时(库更可能更新,语言更多)。

1 个答案:

答案 0 :(得分:1)

(仅为一个时区执行此操作太麻烦了。) 这将返回具有当前dst规则的美国时区的字符串。

您需要为添加的任何区域设置dst开始和结束规则

Date.toTZString= function(d, tzp){
    var short_months= ['Jan', 'Feb', 'Mar', 'Apr', 'May',
     'Jun', 'Jul','Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
    var h, m, pm= 'pm', off, label, str,
    d= d? new Date(d):new Date();

    var tz={
        AK:['Alaska', -540],
        A:['Atlantic', -240],
        C:['Central', -360],
        E:['Eastern', -300],
        HA:['Hawaii-Aleutian', -600],
        M:['Mountain', -420],
        N:['Newfoundland', -210],
        P:['Pacific', -480]
    }[tzp.toUpperCase()];

    //get the selected offset from the object:
    if(!tz) return d.toUTCString();
    off= tz[1];

    //get the start and end dates for dst:(these rules are US only)
    var     y= d.getUTCFullYear(), countstart= 8, countend= 1,
    dstart= new Date(Date.UTC(y, 2, 8, 2, 0, 0, 0)),
    dend= new Date(Date.UTC(y, 10, 1, 2, 0, 0, 0));
    while(dstart.getUTCDay()!== 0) dstart.setUTCDate(++countstart);
    while(dend.getUTCDay()!== 0) dend.setUTCDate(++countend);

    //get the GMT time for the localized dst start and end times:
    dstart.setUTCMinutes(off);
    dend.setUTCMinutes(off);

    // if the date passed in is between dst start and dst end, adjust the offset and label:
    if(dstart<= d && dend>= d){
        off+= 60;
        label= tzp+'dt';
    }
    else label= tzp+'st';

    //add the adjusted offset to the date and get the hours and minutes:
    d.setUTCMinutes(d.getUTCMinutes()+off);
    h= d.getUTCHours();
    m= d.getUTCMinutes();
    if(h> 12) h-= 12;
    else if(h!== 12) pm= 'am';
    if(h== 0) h= 12;
    if(m<10) m= '0'+m;

    //return a string:
    var str= short_months[d.getUTCMonth()]+' '+d.getUTCDate()+', ';
    return str+ h+':'+m+' '+pm+' '+label.toUpperCase();
}



//test1:
var d= new Date().toUTCString();
[d, Date.toTZString(d, 'E'), Date.toTZString(d, 'P')].join('\n');


Mon, 12 Mar 2012 17:46:30 GMT
Mar 12, 1:46 pm EDT
Mar 12, 10:46 am PDT

//test2:
var d=new Date(1352134800000).toUTCString();
[d,Date.toTZString(d, 'E'),Date.toTZString(d, 'P')].join('\n');


Mon, 05 Nov 2012 17:00:00 GMT
Nov 5, 12:00 pm EST
Nov 5, 9:00 am PST