从服务器我得到一个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)"

这对我来说很管用:

function convertUTCDateToLocalDate(date) {
    var newDate = new Date(date.getTime() - date.getTimezoneOffset()*60*1000);
    return newDate;   
}

使用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到本地时间

let a = new Date() .toString a = a.getFullYear () () + "-" + ( a.getMonth () + 1) .toString()。padStart(2, "0") + "-" + a.getDate(). tostring()。padStart(“0”) console.log (a)

在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