从服务器我得到一个datetime变量的格式:6/29/2011 4:52:48 PM,它是UTC时间。我想使用JavaScript将其转换为当前用户的浏览器时区。
如何使用JavaScript或jQuery来做到这一点?
从服务器我得到一个datetime变量的格式:6/29/2011 4:52:48 PM,它是UTC时间。我想使用JavaScript将其转换为当前用户的浏览器时区。
如何使用JavaScript或jQuery来做到这一点?
当前回答
对于TypeScript用户,这里有一个helper函数:
// Typescript Type: Date Options
interface DateOptions {
day: 'numeric' | 'short' | 'long',
month: 'numeric',
year: 'numeric',
timeZone: 'UTC',
};
// Helper Function: Convert UTC Date To Local Date
export const convertUTCDateToLocalDate = (date: Date) => {
// Date Options
const dateOptions: DateOptions = {
day: 'numeric',
month: 'numeric',
year: 'numeric',
timeZone: 'UTC',
};
// Formatted Date (4/20/2020)
const formattedDate = new Date(date.getTime() - date.getTimezoneOffset() * 60 * 1000).toLocaleString('en-US', dateOptions);
return formattedDate;
};
其他回答
在最后添加时区,在本例中是'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"
在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)"
使用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文档。)
对我来说,最简单的方法似乎很有用
datetime.setUTCHours(datetime.getHours());
datetime.setUTCMinutes(datetime.getMinutes());
(我认为第一行可以足够了,但有时区,在几个小时的分数)
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对象。