[英]Determine Whether Daylight Savings Time (DST) is Active in Java for a Specified Date
我有一个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 (参见教程 )版本的正确答案 mamboking 。
ZoneId
表示时区。 该类知道判断DST是否适用于特定时区的规则 。 ZoneRules
类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() );
注意在最后一行中我们如何通过简单调用toInstant
从ZonedDateTime
对象中提取Instant
对象。
java.time框架内置于Java 8及更高版本中。 这些类取代了麻烦的旧遗留日期时间类,如java.util.Date
, Calendar
和SimpleDateFormat
。
现在处于维护模式的Joda-Time项目建议迁移到java.time类。
要了解更多信息,请参阅Oracle教程 。 并搜索Stack Overflow以获取许多示例和解释。 规范是JSR 310 。
您可以直接与数据库交换java.time对象。 使用符合JDBC 4.2或更高版本的JDBC驱动程序 。 不需要字符串,不需要java.sql.*
类。
从哪里获取java.time类?
ThreeTen-Extra项目使用其他类扩展了java.time。 该项目是未来可能添加到java.time的试验场。 您可以在这里找到一些有用的类,比如Interval
, YearWeek
, YearQuarter
,和更多 。
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 )
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.