确定在 Java 中指定日期的夏令时(DST)是否处于活动状态

我有一个 Java 类,它接受位置的纬度/经度,并在夏时制开启和关闭时返回 GMT 偏移量。我正在寻找一个简单的方法,以确定在 Java 中,如果当前的日期是在夏令时,所以我可以应用正确的偏移量。目前我只对美国时区执行这个计算,尽管最终我还是想将其扩展到全球时区。

108983 次浏览

这就是问题所在的机器的答案:

TimeZone.getDefault().inDaylightTime( new Date() );

试图为客户端解决这个问题的服务器将需要客户端的时区。见@Powerlord 回答原因。

任何特定的时区

TimeZone.getTimeZone( "US/Alaska").inDaylightTime( new Date() );
TimeZone tz = TimeZone.getTimeZone("EST");
boolean inDs = tz.inDaylightTime(new Date());

你还得用这些坐标做更多的工作找出他们在哪个时区。一旦知道了 TimeZone 是哪个,isDayLight ()方法就会非常有用。

例如,你无法判断 -0500是否是 EST (美国/加拿大东部标准时间)、 CDT (美国/加拿大 UTC-5)、 COT (哥伦比亚时间)、 AST (巴西英亩标准时间)、 ECT (厄瓜多尔时间)等等。.

其中一些可能支持也可能不支持夏时制。

Joda Time 包含为您计算偏移量的处理方法。请参见 < a href = “ http://Joda-Time.sourceforge.net/api-release/org/Joda/Time/DateTimeZone.html”rel = “ nofollow noReferrer”> DateTimeZone.ConvertLocalToUTC (...)

为了补充这一点,您将需要查找当前的时区与您的经纬度信息。地名为其 Web 服务提供了一个 java 客户端,以及一个简单的 Web 请求框架(即 http://ws.geonames.org/timezone?lat=47.01&lng=10.2)

博士

ZoneId.of( "America/Montreal" )  // Represent a specific time zone, the history of past, present, and future changes to the offset-from-UTC used by the people of a certain region.
.getRules()                // Obtain the list of those changes in offset.
.isDaylightSavings(        // See if the people of this region are observing Daylight Saving Time at a specific moment.
Instant.now()          // Specify the moment. Here we capture the current moment at runtime.
)                          // Returns a boolean.

爪哇时间

这里是现代的 爪哇时间(见 教程)版本的 正确答案赌博

示例代码:

ZonedDateTime now = ZonedDateTime.now( ZoneId.of( "America/Montreal" ) );
…
ZoneId z = now.getZone();
ZoneRules zoneRules = z.getRules();
Boolean isDst = zoneRules.isDaylightSavings( now.toInstant() );

请注意,在最后一行中,我们必须通过对 toInstant的简单调用从 ZonedDateTime对象中提取一个 Instant对象。

Table of date-time types in Java, both modern and legacy.


关于 爪哇时间

< em > java.time 框架内置于 Java8及更高版本中。这些类取代了令人讨厌的旧的 遗产日期时间类,如 java.util.DateCalendarSimpleDateFormat

现在在 维修模式中的 尤达时间项目建议迁移到 爪哇时间类。

要了解更多,请参阅 < em > Oracle 教程 。并搜索堆栈溢出许多例子和解释。规范是 JSR 310

您可以直接与数据库交换 爪哇时间对象。使用与 JDBC 4.2或更高版本兼容的 JDBC 驱动程序。不需要字符串,不需要 java.sql.*类。

从哪里获得 java.time 类?

< strong > Three Ten-Ultra 项目使用其他类扩展 java.time。这个项目是将来可能添加 java.time 的试验场。您可以在这里找到一些有用的类,比如 IntervalYearWeekYearQuarter更多