从服务器我得到一个datetime变量的格式:6/29/2011 4:52:48 PM,它是UTC时间。我想使用JavaScript将其转换为当前用户的浏览器时区。
如何使用JavaScript或jQuery来做到这一点?
从服务器我得到一个datetime变量的格式:6/29/2011 4:52:48 PM,它是UTC时间。我想使用JavaScript将其转换为当前用户的浏览器时区。
如何使用JavaScript或jQuery来做到这一点?
当前回答
我在safari/chrome/firefox浏览器中使用这种方法效果很好:
const localDate = new Date(`${utcDate.replace(/-/g, '/')} UTC`);
其他回答
JSON日期字符串(在c#中序列化)看起来像“2015-10-13T18:58:17”。
在angular中,(遵循Hulvej)创建一个localdate过滤器:
myFilters.filter('localdate', function () {
return function(input) {
var date = new Date(input + '.000Z');
return date;
};
})
然后,像这样显示本地时间:
{{order.createDate | localdate | date : 'MMM d, y h:mm a' }}
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对象。
我在safari/chrome/firefox浏览器中使用这种方法效果很好:
const localDate = new Date(`${utcDate.replace(/-/g, '/')} UTC`);
将此用于UTC和本地时间转换,反之亦然。
//Covert datetime by GMT offset
//If toUTC is true then return UTC time other wise return local time
function convertLocalDateToUTCDate(date, toUTC) {
date = new Date(date);
//Local time converted to UTC
console.log("Time: " + date);
var localOffset = date.getTimezoneOffset() * 60000;
var localTime = date.getTime();
if (toUTC) {
date = localTime + localOffset;
} else {
date = localTime - localOffset;
}
date = new Date(date);
console.log("Converted time: " + date);
return date;
}
UTC到本地到ISO -使用Molp Burnbright回答
因为服务器只接受ISO日期-时间,所以我将UTC转换为我的本地时区,并以ISO格式发送给服务器
在某处声明
function convertUTCDateToLocalDate(date) {
var newDate = new Date(date.getTime() - date.getTimezoneOffset()*60*1000);
return newDate;
}
并在需要ISO格式的本地日期时间时执行此操作。