从服务器我得到一个datetime变量的格式:6/29/2011 4:52:48 PM,它是UTC时间。我想使用JavaScript将其转换为当前用户的浏览器时区。

如何使用JavaScript或jQuery来做到这一点?


当前回答

你可以使用momentjs,moment(date).format()总是会给出本地日期的结果。

额外的好处是,你可以以任何你想要的方式格式化。如。

moment().format('MMMM Do YYYY, h:mm:ss a'); // September 14th 2018, 12:51:03 pm
moment().format('dddd');                    // Friday
moment().format("MMM Do YY"); 

更多细节请参考Moment js网站

其他回答

你可以使用momentjs,moment(date).format()总是会给出本地日期的结果。

额外的好处是,你可以以任何你想要的方式格式化。如。

moment().format('MMMM Do YYYY, h:mm:ss a'); // September 14th 2018, 12:51:03 pm
moment().format('dddd');                    // Friday
moment().format("MMM Do YY"); 

更多细节请参考Moment js网站

在最后添加时区,在本例中是'UTC':

theDate = new Date( Date.parse('6/29/2011 4:52:48 PM UTC'));

之后,使用toLocale()*函数族以正确的地区显示日期

theDate.toLocaleString();  // "6/29/2011, 9:52:48 AM"
theDate.toLocaleTimeString();  // "9:52:48 AM"
theDate.toLocaleDateString();  // "6/29/2011"

将此用于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;
}

在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)"

在JavaScript中,我使用:

var updaated_time= "2022-10-25T06:47:42.000Z"

{{updaated_time | date: 'dd-MM-yyyy HH:mm'}} //output: 26-10-2022 12:00