关于Javascript的重要知识是,所有对时区的引用指的是系统中执行代码的时区,其中您无法控制。你甚至不能相信客户端机器设置了正确的时区。所以当你选择一个显示时区的选项时,所有可以完成的事情都是给你客户端的时区。
JavaScript中的时区可能会变得很复杂,这里有一个,它有相当多的细节并提供解决方案。
处理时区的一种简单方法是将所有日期存储在UTC中,然后使用moment.JS库格式化它们以显示它们。假设您的所有时间都以UTC格式存储,则可以使用类似this plunker中所写的过滤器来格式化日期并将其操作为用户首选的时区。这里只是样品过滤件代码:
// filter to set the timezone, assumes incoming time is in UTC
angular
.module('plunker')
.filter('toUserTimezone', function() {
return function(input, format, offset) {
var output, timezoneText, inputCopy;
// we need to copy the object so we don't cause any side-effects
inputCopy = angular.copy(input);
// check to make sure a moment object was passed
if (!moment.isMoment(inputCopy)) {
// do nothing
return input;
} else {
// set default offset change to 0
offset = offset || 0;
// change the time by the offet
inputCopy.add(offset, 'hours');
// this will need to be improved so the added text is in the format +hh:mm
offset >= 0 ? timezoneText = '+' + offset : timezoneText = offset;
// format the output to the requested format and add the timezone
output = inputCopy.format(format) + ' ' + timezoneText;
return output;
}
};
});
的那一刻库是相当不错的,只要我有日期的工作,我会包含它,因为它是小的。它也有一些非常强大的时区工具。您可以使用时区工具扩展上面的过滤器,以使其与DST以及偏移量不等于一小时的时区(如印度)一起工作。
更新: 在看了时区库之后,我们实际上可以简化过滤器代码。第一个解决方案更多的是破解,这个解决方案更加强大,因为我们将保留原始时区数据。另外,我已将格式和时区转换为两个单独的过滤器。您可以在this plunker中看到演示。
这里是转换时区的过滤器:
angular
.module('plunker')
.filter('convertTimezone', function() {
return function(input, timezone) {
var output;
// use clone to prevent side-effects
output = input.clone().tz(timezone);
// if the timezone was not valid, moment will not do anything, you may
// want this to log if there was an issue
if (moment.isMoment(output)) {
return output;
} else {
// log error...
return input;
}
};
});
的时区库允许您将字符串传递到moment.tz()方法,如果该字符串被称为转换会发生,如果不是无将作出更改。克隆()方法是防止使用angular.copy的副作用的一种更好的方法,就像我以前那样。
现在,这里是新的格式,滤镜,与前:
angular
.module('plunker')
.filter('formatTime', function() {
return function(input, format) {
// check to make sure a moment object was passed
if (!moment.isMoment(input)) {
// do nothing
return input;
} else {
return input.format(format);
}
};
});
综上所述,当下时区图书馆是非常有用的!
谢谢,这看起来不错!你是否可以说例如在偏移量中传递“欧洲/都柏林”,然后像在时区选择中一样计算该值的偏移量? –
答案是可以的,如果你使用moment.JS时区库。查看我更新的新过滤器和新演示的答案。 – Graham
谢谢!它看起来非常棒! –