在 JavaScript 中是否可以将 Date 对象保存在不同的时区,例如:
date1.toString();
>>> 2012-02-16T14:00+02:00
date2.toString();
>>> 2012-03-16T13:00+01:00
即我有两个日期对象,它们反射(reflect)同一时刻的时间,但将它们的信息保存在不同的时区。
最佳答案
没有。 JavaScript 中的日期代表一个时刻;他们不存储时区信息。然后,您可以选择显示特定时区中代表的时间。 (参见 getHours()
等各种方法——当前本地时区——与 getUTCHours()
的对比。)
要显示 UTC 或本地以外时区的时间,您需要编写(或使用)一个函数来做一些数学运算:
function offsetDate( date, hours ){
return date.setUTCHours( date.getUTCHours() + hours );
}
编辑:您可以选择存储自定义偏移量和日期(因为您可以向任何 JS 对象添加自定义属性):
Date.prototype.withZone = function(){
var o = new Date(this.getTime()); // Make a copy for mutating
o.setUTCHours(o.getUTCHours() + (this.tz || 0)); // Move the UTC time
// Return a custom formatted version of the date
var offset = this.tz ? (this.tz<0 ? this.tz : ('+'+this.tz)) : 'Z';
return o.customFormat('#YYYY#-#MMM#-#D# @ #h#:#mm##ampm# ('+offset+')');
}
// http://phrogz.net/JS/FormatDateTime_js.txt
Date.prototype.customFormat = function(formatString){
var YYYY,YY,MMMM,MMM,MM,M,DDDD,DDD,DD,D,hhh,hh,h,mm,m,ss,s,ampm,AMPM,dMod,th;
YY = ((YYYY=this.getUTCFullYear())+"").slice(-2);
MM = (M=this.getUTCMonth()+1)<10?('0'+M):M;
MMM = (MMMM=["January","February","March","April","May","June","July","August","September","October","November","December"][M-1]).substring(0,3);
DD = (D=this.getUTCDate())<10?('0'+D):D;
DDD = (DDDD=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"][this.getUTCDay()]).substring(0,3);
th=(D>=10&&D<=20)?'th':((dMod=D%10)==1)?'st':(dMod==2)?'nd':(dMod==3)?'rd':'th';
formatString = formatString.replace("#YYYY#",YYYY).replace("#YY#",YY).replace("#MMMM#",MMMM).replace("#MMM#",MMM).replace("#MM#",MM).replace("#M#",M).replace("#DDDD#",DDDD).replace("#DDD#",DDD).replace("#DD#",DD).replace("#D#",D).replace("#th#",th);
h=(hhh=this.getUTCHours());
if (h==0) h=24; if (h>12) h-=12;
hh = h<10?('0'+h):h;
AMPM=(ampm=hhh<12?'am':'pm').toUpperCase();
mm=(m=this.getUTCMinutes())<10?('0'+m):m;
ss=(s=this.getUTCSeconds())<10?('0'+s):s;
return formatString.replace("#hhh#",hhh).replace("#hh#",hh).replace("#h#",h).replace("#mm#",mm).replace("#m#",m).replace("#ss#",ss).replace("#s#",s).replace("#ampm#",ampm).replace("#AMPM#",AMPM);
}
var now = new Date; // Make a plain date
console.log( now.withZone() ); //-> 2012-Feb-16 @ 9:37pm (Z)
now.tz = -7; // Add a custom property for our method to use
console.log( now.withZone() ); //-> 2012-Feb-16 @ 2:37pm (-7)
关于javascript - 如何在 JavaScript 中将 Date 对象保存在不同的时区,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9318198/