从服务器我得到一个datetime变量的格式:6/29/2011 4:52:48 PM,它是UTC时间。我想使用JavaScript将其转换为当前用户的浏览器时区。
如何使用JavaScript或jQuery来做到这一点?
从服务器我得到一个datetime变量的格式:6/29/2011 4:52:48 PM,它是UTC时间。我想使用JavaScript将其转换为当前用户的浏览器时区。
如何使用JavaScript或jQuery来做到这一点?
当前回答
如果你不介意使用moment.js,并且你的时间是UTC时间,请使用以下格式:
moment.utc('6/29/2011 4:52:48 PM').toDate();
如果您的时间不是utc,而是您所知道的任何其他地区,则使用以下方法:
moment('6/29/2011 4:52:48 PM', 'MM-DD-YYYY', 'fr').toDate();
如果你的时间已经在本地,那么使用以下方法:
moment('6/29/2011 4:52:48 PM', 'MM-DD-YYYY');
其他回答
在Angular中,我这样使用Ben的回答:
$scope.convert = function (thedate) {
var tempstr = thedate.toString();
var newstr = tempstr.toString().replace(/GMT.*/g, "");
newstr = newstr + " UTC";
return new Date(newstr);
};
编辑:Angular 1.3.0添加了UTC日期过滤器,我还没有使用过,但它应该更简单,格式如下:
{{ date_expression | date : format : timezone}}
Angular 1.4.3 Date API
function getUTC(str) {
var arr = str.split(/[- :]/);
var utc = new Date(arr[0], arr[1]-1, arr[2], arr[3], arr[4], arr[5]);
utc.setTime(utc.getTime() - utc.getTimezoneOffset()*60*1000)
return utc;
}
对于其他访问的人-使用此函数从UTC字符串中获取本地日期对象,应该关心DST,并将在IE, IPhone等上工作。
我们分割字符串(因为JS日期解析在某些浏览器上不支持) 我们得到UTC的差值,然后用UTC时间减去它,得到当地时间。由于返回的偏移量是用DST计算的(如果我错了请纠正我),所以它将在变量“utc”中设置该时间。最后返回date对象。
UTC到本地到ISO -使用Molp Burnbright回答
因为服务器只接受ISO日期-时间,所以我将UTC转换为我的本地时区,并以ISO格式发送给服务器
在某处声明
function convertUTCDateToLocalDate(date) {
var newDate = new Date(date.getTime() - date.getTimezoneOffset()*60*1000);
return newDate;
}
并在需要ISO格式的本地日期时间时执行此操作。
以下是基于Adorjan Princ的回答的简化解决方案:
function convertUTCDateToLocalDate(date) {
var newDate = new Date(date);
newDate.setMinutes(date.getMinutes() - date.getTimezoneOffset());
return newDate;
}
或者更简单(尽管它会改变原始日期):
function convertUTCDateToLocalDate(date) {
date.setMinutes(date.getMinutes() - date.getTimezoneOffset());
return date;
}
用法:
var date = convertUTCDateToLocalDate(new Date(date_string_you_received));
这是一个普遍的解决方案:
function convertUTCDateToLocalDate(date) {
var newDate = new Date(date.getTime()+date.getTimezoneOffset()*60*1000);
var offset = date.getTimezoneOffset() / 60;
var hours = date.getHours();
newDate.setHours(hours - offset);
return newDate;
}
用法:
var date = convertUTCDateToLocalDate(new Date(date_string_you_received));
根据客户端本地设置显示日期:
date.toLocaleString();