从服务器我得到一个datetime变量的格式:6/29/2011 4:52:48 PM,它是UTC时间。我想使用JavaScript将其转换为当前用户的浏览器时区。
如何使用JavaScript或jQuery来做到这一点?
从服务器我得到一个datetime变量的格式:6/29/2011 4:52:48 PM,它是UTC时间。我想使用JavaScript将其转换为当前用户的浏览器时区。
如何使用JavaScript或jQuery来做到这一点?
当前回答
采用YYYY-MM-DD hh:mm:ss格式:
var date = new Date('2011-06-29T16:52:48+00:00');
date.toString() // "Wed Jun 29 2011 09:52:48 GMT-0700 (PDT)"
要从YYYY-MM-DD hh:mm:ss格式转换,请确保您的日期遵循ISO 8601格式。
Year:
YYYY (eg 1997)
Year and month:
YYYY-MM (eg 1997-07)
Complete date:
YYYY-MM-DD (eg 1997-07-16)
Complete date plus hours and minutes:
YYYY-MM-DDThh:mmTZD (eg 1997-07-16T19:20+01:00)
Complete date plus hours, minutes and seconds:
YYYY-MM-DDThh:mm:ssTZD (eg 1997-07-16T19:20:30+01:00)
Complete date plus hours, minutes, seconds and a decimal fraction of a second
YYYY-MM-DDThh:mm:ss.sTZD (eg 1997-07-16T19:20:30.45+01:00) where:
YYYY = four-digit year
MM = two-digit month (01=January, etc.)
DD = two-digit day of month (01 through 31)
hh = two digits of hour (00 through 23) (am/pm NOT allowed)
mm = two digits of minute (00 through 59)
ss = two digits of second (00 through 59)
s = one or more digits representing a decimal fraction of a second
TZD = time zone designator (Z or +hh:mm or -hh:mm)
需要注意的重要事项
你必须用T分隔日期和时间,空格在某些浏览器中不起作用 您必须使用这种格式+hh:mm设置时区,使用字符串作为时区(例如:'UTC')将在许多浏览器中不起作用。+hh:mm表示与UTC时区的偏移量。
其他回答
在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();
然后对从服务器得到的时间做相应的加减运算。
希望这能有所帮助。
我相信这是最好的解决方案:
let date = new Date(objDate);
date.setMinutes(date.getTimezoneOffset());
这将根据偏移量适当地更新您的日期,因为它是以分钟为单位的。
在最后添加时区,在本例中是'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"
如果你有
“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的更多信息