从服务器我得到一个datetime变量的格式:6/29/2011 4:52:48 PM,它是UTC时间。我想使用JavaScript将其转换为当前用户的浏览器时区。
如何使用JavaScript或jQuery来做到这一点?
从服务器我得到一个datetime变量的格式:6/29/2011 4:52:48 PM,它是UTC时间。我想使用JavaScript将其转换为当前用户的浏览器时区。
如何使用JavaScript或jQuery来做到这一点?
当前回答
UTC到本地到ISO -使用Molp Burnbright回答
因为服务器只接受ISO日期-时间,所以我将UTC转换为我的本地时区,并以ISO格式发送给服务器
在某处声明
function convertUTCDateToLocalDate(date) {
var newDate = new Date(date.getTime() - date.getTimezoneOffset()*60*1000);
return newDate;
}
并在需要ISO格式的本地日期时间时执行此操作。
其他回答
对于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)偏移量(分钟)的客户端:
var offset = new Date().getTimezoneOffset();
然后对从服务器得到的时间做相应的加减运算。
希望这能有所帮助。
UTC到本地到ISO -使用Molp Burnbright回答
因为服务器只接受ISO日期-时间,所以我将UTC转换为我的本地时区,并以ISO格式发送给服务器
在某处声明
function convertUTCDateToLocalDate(date) {
var newDate = new Date(date.getTime() - date.getTimezoneOffset()*60*1000);
return newDate;
}
并在需要ISO格式的本地日期时间时执行此操作。
tl;dr (new Date('6/29/2011 4:52:48 PM UTC')).toString()
源字符串必须指定时区或UTC。
一行程序:
(new Date('6/29/2011 4:52:48 PM UTC')).toString()
结果在我的一个web浏览器:
"Wed Jun 29 2011 09:52:48 GMT-0700 (Pacific Daylight Time)"
这种方法甚至适当地选择标准/日光时间。
(new Date('1/29/2011 4:52:48 PM UTC')).toString()
结果在我的浏览器:
"Sat Jan 29 2011 08:52:48 GMT-0800 (Pacific Standard Time)"
把这个函数记在脑子里:
<script type="text/javascript">
function localize(t)
{
var d=new Date(t+" UTC");
document.write(d.toString());
}
</script>
然后为页面主体中的每个日期生成以下内容:
<script type="text/javascript">localize("6/29/2011 4:52:48 PM");</script>
删除GMT和时区,修改以下行:
document.write(d.toString().replace(/GMT.*/g,""));