我有一个Java类,它接收位置的纬度/经度,并在夏令时开启和关闭时返回GMT偏移。我正在寻找一种简单的方法来确定Java中当前日期是否为夏令时,因此我可以应用正确的偏移量。目前我只对美国时区执行此计算,但最终我还希望将其扩展到全球时区。
这是问题所在机器的答案:
TimeZone.getDefault().inDaylightTime( new Date() );
试图为客户端解决这个问题的服务器需要客户端的时区。请参阅@Powerlord的答案。
对于任何特定的TimeZone
TimeZone.getTimeZone( "US/Alaska").inDaylightTime( new Date() );
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.
这是java.time的现代Tutorial(参见correct Answer)版本的mamboking。
ZoneId
代表一个时区。该类知道如果DST适用于a particular time zone的规则。ZoneRules
类为时区的所有历史和未来过渡建模。Instant
是UTC时间轴上的一个时刻。ZonedDateTime
是将ZoneId
应用于Instant
的结果。示例代码:
ZonedDateTime now = ZonedDateTime.now( ZoneId.of( "America/Montreal" ) );
…
ZoneId z = now.getZone();
ZoneRules zoneRules = z.getRules();
Boolean isDst = zoneRules.isDaylightSavings( now.toInstant() );
注意在最后一行我们如何通过简单调用Instant
从ZonedDateTime
对象中提取toInstant
对象。
java.time框架内置于Java 8及更高版本中。这些类取代了麻烦的旧legacy日期时间类,如java.util.Date
,Calendar
和SimpleDateFormat
。
现在在Joda-Time的maintenance mode项目建议迁移到java.time班。
要了解更多信息,请参阅Oracle Tutorial。并搜索Stack Overflow以获取许多示例和解释。规格是JSR 310。
您可以直接与数据库交换java.time对象。使用符合JDBC driver或更高版本的JDBC 4.2。不需要字符串,不需要java.sql.*
类。
从哪里获取java.time类?
ThreeTen-Extra项目使用其他类扩展了java.time。该项目是未来可能添加到java.time的试验场。你可能会在这里找到一些有用的类,如Interval
,YearWeek
,YearQuarter
和more。
TimeZone tz = TimeZone.getTimeZone("EST");
boolean inDs = tz.inDaylightTime(new Date());
你将不得不使用这些坐标做更多的工作,并找出它们所在的时区。一旦你知道了哪个TimeZone,isDayLight()方法将是有用的。
例如,您无法分辨-0500是EST(美国/加拿大东部标准时间),CDT(美国/加拿大中部夏令时),COT(哥伦比亚时间),AST(巴西英亩标准时间),ECT(厄瓜多尔)时间)等......
其中一些可能支持也可能不支持夏令时。
Joda Time包含处理方法,可以为您计算偏移量。见DateTimeZone.convertLocalToUTC(...)
要补充这一点,您需要使用纬度/经度信息查找当前时区。 GeoNames为其Web服务提供了一个Java客户端,以及一个简单的Web请求框架(即http://ws.geonames.org/timezone?lat=47.01&lng=10.2)