![](/img/trans.png)
[英]How to get client timezone in utc format like (UTC+05:00) in php or javascript
[英]In javascript, how to get timezone value in UTC format for new Date(2017,05,31).toISOString()?
如何获取新 Date(2017,05,31).toISOString() 的时区值?当将日期传递给 Date 构造函数时,对于任何 Date ,它总是以 000Z 的形式出现。但是对于 new Date().toISOString(),它给出了时区值。
new Date(2017,05,31).toISOString() gives "2017-05-30T18:30:00.000Z"
如果您希望时间默认为 UTC 午夜,您可以使用Date.UTC(year, month, ...)
首先创建基于 UTC 的时间戳。
var utcMay31 = Date.UTC(2017, 4, 31); // note: 4 = May (0 = January)
然后,从该时间戳创建Date
。
new Date(utcMay31).toUTCString(); // "Wed, 31 May 2017 00:00:00 GMT"
但是,如果您想知道存储在Date
对象中的时区,它实际上并没有。 Date
s 表示时间上的“瞬间”,即自 1970 年 1 月 1 日 00:00:00.000 UTC 以来经过的总毫秒数。
new Date().getTime(); // 1496851...
Date
可以告诉您用户在该时刻与 UTC 的本地偏移量(以分钟为单位)。
new Date().getTimezoneOffset(); // e.g. 0, -480, 300
否则,在创建日期字符串时,时区仅限于两种选择,并且选择基于使用的方法 - 用户的本地时区或 UTC。
new Date().toString(); // "now" in user's local time
new Date().toUTCString(); // "now" in UTC time
new Date().toISOString(); // "now" also in UTC time, alternate format
// etc.
您很困惑 ISO 日期值不显示“时区”,而是显示 UTC 时间。 Z 代表祖鲁语(UTC 时间)。
2017-06-07T15:29:23。 692Z
粗体部分不是时区。 它是毫秒,完整时间是 UTC。 它在设置日期中显示 000Z 的原因是因为您没有设置毫秒。
如果要显示时区,请使用 toUTCString()。 但是,它将显示 GMT,即 UTC/格林威治时间。 要以日期格式显示本地时区,您可以使用 date.toLocaleString('en-US',{timeZoneName:'short'}) 例如将显示日期加上美国本地时区。 或者您可以使用 toString() 来显示 GMT 偏移量 + 本地长时区。
在 javascript 中,解析、渲染和构造日期将始终假定为本地日期。 它将转换为时间戳,即自 1970 年 1 月 1 日 00:00:00 以来的毫秒数。 JSON.stringify 将转换为 UTC 字符串,但旧版框架使用本地日期。 始终提防这一点。
var myDate = new Date(); // this is now.
您可以使用myDate.getTimezoneOffset()
获取您的时区偏移量(以分钟为myDate.getTimezoneOffset()
,但这将为每个日期返回相同的偏移量(夏令时除外)
你不应该这样做:
var utcDate = new Date(+d+60000*d.getTimezoneOffset());
// +d convert the date to a timespan.
// getTimezoneOffset() is in minutes
// *60000 makes that in milliseconds, the scale timespans operate upon
Date 有几种格式化日期的方法,但总是使用本地或 UTC 日期。 如果您想要不同的时区,则需要手动完成。
注意: Date.UTC(...)
函数返回一个时间戳。 您有时会看到日期偏移,因此它们的行为类似于 UTC。 但这会在以后引起问题。
var date = new Date(2000,1,1,12,0,0);
// DO NOT USE (breaks at start of daylight saving time)
// these are date/times that have the UTC-value,
// but Javascript treats them like local dates with this value.
utcDate1 = (+date-60000*d.getTimeZoneOffset()); // minus!!
utcDate2 = new Date(Date.UTC(2000,1,1,12,0,0));
// DO NOT USE (breaks at start of daylight saving time)
顺便说一句,Edge、Chrome 和 Firefox 在控制台中显示日期的方式不同:Edge 和 Firefox 始终显示本地日期,Chrome 显示 UTC。 此外,如果您更改时区,Edge 会搞砸。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.