2012-03-12 15 views
0

現在の日付と時刻を東部時間に取得する方法はありますか?現時点と目標のタイムゾーンで夏時間を考慮していますか?ETの現在の日付/時刻

もちろん、現在のタイムゾーンがニューヨーク(ESTまたはEDT)で使用されているかどうかを確認することが難しいです。 Javascriptでこれを行うことはできますか?それとも良いライブラリがありますか?私は、新しい法律が渡されたとき(ライブラリが更新される可能性が高く、言語がまだまだある)、コードが古くなってしまうため、計算をハードコーディングすることには注意が必要です。

+0

追加したゾーンのDSTの開始と終了のルールが必要になりますあなたが特定の時刻を表示し、ユーザーのシステムからの時間を使用しないようにしたいですか? –

+0

あなたの答えはhttp://www.w3schools.com/js/js_obj_date.aspで見つけることができます – Hope4You

+0

@MartínCanaval:はい、正しい。わかりやすくするために、「現在の夏時間調整時間はニューヨークです:_____」というダイアログを表示しています。 – Charles

答えて

1

これは、現在の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 
+0

現地時間帯と東部時間の日付が異なる場合、日付が正しく転記されますか? – Charles

関連する問題