nem*_*_87 53 javascript momentjs angular-moment
使用moment.js和moment-timezone.js时,获取客户端时区并将其转换为其他时区的最佳方法是什么?
我想找出什么是客户时区,然后将其日期和时间转换为其他时区.
有没有人有这方面的经验?
Mat*_*int 173
使用moment.js时,请使用:
var tz = moment.tz.guess();
Run Code Online (Sandbox Code Playgroud)
它将返回IANA时区标识符,例如America/Los_Angeles美国太平洋时区.
这是记录在这里.
jog*_*goe 12
var timedifference = new Date().getTimezoneOffset();
这将返回客户端时区与UTC时间的差异.然后你可以随心所欲地玩它.
使用moment.js时,moment(date).utcOffset()返回浏览器时间与UTC 作为参数传递的日期之间的时间差(以分钟为单位),如果没有传递日期,则返回今天.
不要在变量中设置此差异并将其用于选择的日期:
function getUtcOffset(date) {
return moment(date)
.subtract(
moment(date).utcOffset(),
'minutes')
.utc()
}
Run Code Online (Sandbox Code Playgroud)
以上内容将对您使用的所有日期应用当前差异,如果您在夏令时区,如果它们在一年的另一半,则日期将会减少一个小时.
这是一个在拾取日期解析正确偏移量的函数:
function getUtcOffset(date) {
return moment(date)
.subtract(
moment(date).utcOffset(),
'minutes')
.utc()
}
Run Code Online (Sandbox Code Playgroud)
使用Moment库,请参阅他们的网站 -> https://momentjs.com/timezone/docs/#/using-timezones/converting-to-zone/
我注意到他们还在他们的网站上使用了自己的库,因此您可以在安装之前尝试使用浏览器控制台
moment().tz(String);
The moment#tz mutator will change the time zone and update the offset.
moment("2013-11-18").tz("America/Toronto").format('Z'); // -05:00
moment("2013-11-18").tz("Europe/Berlin").format('Z'); // +01:00
This information is used consistently in other operations, like calculating the start of the day.
var m = moment.tz("2013-11-18 11:55", "America/Toronto");
m.format(); // 2013-11-18T11:55:00-05:00
m.startOf("day").format(); // 2013-11-18T00:00:00-05:00
m.tz("Europe/Berlin").format(); // 2013-11-18T06:00:00+01:00
m.startOf("day").format(); // 2013-11-18T00:00:00+01:00
Without an argument, moment#tz returns:
the time zone name assigned to the moment instance or
undefined if a time zone has not been set.
var m = moment.tz("2013-11-18 11:55", "America/Toronto");
m.tz(); // America/Toronto
var m = moment.tz("2013-11-18 11:55");
m.tz() === undefined; // true
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
72423 次 |
| 最近记录: |