从服务器我得到一个datetime变量的格式:6/29/2011 4:52:48 PM,它是UTC时间。我想使用JavaScript将其转换为当前用户的浏览器时区。
如何使用JavaScript或jQuery来做到这一点?
从服务器我得到一个datetime变量的格式:6/29/2011 4:52:48 PM,它是UTC时间。我想使用JavaScript将其转换为当前用户的浏览器时区。
如何使用JavaScript或jQuery来做到这一点?
当前回答
使用dayjs库:
(new Date()).toISOString(); // returns 2021-03-26T09:58:57.156Z (GMT time)
dayjs().format('YYYY-MM-DD HH:mm:ss,SSS'); // returns 2021-03-26 10:58:57,156 (local time)
(在nodejs中,你必须在使用它之前:const dayjs = require('dayjs'); 在其他环境下,请阅读dayjs文档。)
其他回答
在javascript中将字符串转换为日期之前,将'UTC'附加到字符串中:
var date = new Date('6/29/2011 4:52:48 PM UTC');
date.toString() // "Wed Jun 29 2011 09:52:48 GMT-0700 (PDT)"
你应该得到(UTC)偏移量(分钟)的客户端:
var offset = new Date().getTimezoneOffset();
然后对从服务器得到的时间做相应的加减运算。
希望这能有所帮助。
使用dayjs库:
(new Date()).toISOString(); // returns 2021-03-26T09:58:57.156Z (GMT time)
dayjs().format('YYYY-MM-DD HH:mm:ss,SSS'); // returns 2021-03-26 10:58:57,156 (local time)
(在nodejs中,你必须在使用它之前:const dayjs = require('dayjs'); 在其他环境下,请阅读dayjs文档。)
如果你有
“2021 - 12 - 28 - t18:00:45.959z”格式
你可以在js中使用这个:
// myDateTime is 2021-12-28T18:00:45.959Z
myDate = new Date(myDateTime).toLocaleDateString('en-US');
// myDate is 12/28/2021
myTime = new Date(myDateTime).toLocaleTimeString('en-US');
// myTime is 9:30:45 PM
你只需要输入你的区域字符串而不是“en-US”(例如。“fa-IR”)。
你也可以使用toLocaleTimeString的选项,比如{小时:'2-digit',分钟:'2-digit'}
myTime = new Date(myDateTime).toLocaleTimeString('en-US',{ hour: '2-digit', minute: '2-digit' });
// myTime is 09:30 PM
toLocaleTimeString和toLocaleDateString的更多信息
在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