[英]Timezone Abbreviations in Java
I have a collection of Java Date objects, loaded from an old database which did not store timezone info.我有一个 Java Date对象的集合,从一个没有存储时区信息的旧数据库加载。
I know that all the dates (which include hours, minutes and seconds) are for the US Eastern time zone.我知道所有日期(包括小时、分钟和秒)都是针对美国东部时区的。
I want to derive the correct timezone abbreviation ("EST" or "EDT") for each date.我想为每个日期导出正确的时区缩写(“EST”或“EDT”)。
Here is my attempt (using Java 11).这是我的尝试(使用 Java 11)。 It is unwieldy, to say the least.
至少可以说,这是笨拙的。
I looked into the following classes:我研究了以下课程:
java.util.TimeZone
java.time.ZoneId
java.time.zone.ZoneRules
Here is my method - it uses two statements purely to give me a fighting chance of still understanding what I wrote, a week from now.这是我的方法 - 它使用两个语句纯粹是为了让我有机会在一周后仍然理解我所写的内容。
EDIT - based on @VGR's comment below, I have updated the example.编辑 - 根据下面@VGR 的评论,我更新了示例。 Now it expects a timezone display name - for example
"America/New_York"
:现在它需要一个时区显示名称 - 例如
"America/New_York"
:
public String getTimezoneAbbrev(Date date, String tzName) {
TimeZone tz = TimeZone.getTimeZone(tzName);
boolean isDaylightSavings = tz.toZoneId().getRules().isDaylightSavings(date.toInstant());
return tz.getDisplayName(isDaylightSavings, TimeZone.SHORT);
}
It works (I have test cases), but is there a less verbose way?它有效(我有测试用例),但是有没有一种不那么冗长的方法?
(I did not find any code examples which use Date
as their starting point). (我没有找到任何使用
Date
作为起点的代码示例)。
Something like the following?像下面这样的?
import java.util.Date;
import java.util.TimeZone;
public class Main {
public static void main(String[] args) {
System.out.println(TimeZone.getDefault().getDisplayName(TimeZone.getDefault().inDaylightTime(new Date()),TimeZone.SHORT));
}
}
I have accepted Arvind's answer because he pointed out TimeZone.inDaylightTime()
- but for the record, here is the updated version of the method in my question.我已经接受了 Arvind 的回答,因为他指出了
TimeZone.inDaylightTime()
- 但为了记录,这里是我问题中方法的更新版本。
It is more concise now:现在更简洁:
// tzName is a timezone display name, such as "America/New_York"
public static String getTimezoneAbbrev(Date date, String tzName) {
TimeZone tz = TimeZone.getTimeZone(tzName);
return tz.getDisplayName(tz.inDaylightTime(date), TimeZone.SHORT);
}
I also found answers in this question helpful - because if you type a non-existent timezone display name (or ID) when using TimeZone.getTimeZone(), Java will return "the specified TimeZone, or the GMT zone if the given ID cannot be understood" (emphasis mine).我还发现这个问题中的答案很有帮助 - 因为如果您在使用 TimeZone.getTimeZone() 时键入不存在的时区显示名称(或 ID),Java 将返回“指定的时区或 GMT 时区,如果给定的 ID 不能是理解”(强调我的)。 See here .
见这里。
Typing...正在输入...
America/New-York
...instead of... ...代替...
America/New_York
...is enough to cause problems. ......足以引起问题。
We should usejava.time.ZoneId
instead.我们应该使用
java.time.ZoneId
代替。 This will throw an error for an invalid/unknown ID.这将引发无效/未知 ID 的错误。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.