确定 Java 中指定日期的夏令时 (DST) 是否有效

发布于 2024-07-25 22:42:15 字数 140 浏览 15 评论 0 原文

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

I have a Java class that takes in the latitude/longitude of a location and returns the GMT offset when daylight savings time is on and off. I am looking for an easy way to determine in Java if the current date is in daylight savings time so I can apply the correct offset. Currently I am only performing this calculation for U.S. timezones although eventually I would like to expand this to global timezones as well.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

别靠近我心 2024-08-01 22:42:15

这是提出问题的机器的答案:

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

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

对于任何特定时区

TimeZone.getTimeZone( "US/Alaska").inDaylightTime( new Date() );

This is the answer for the machine on which the question is being asked:

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

A server trying to figure this out for a client will need the client's time zone. See @Powerlord answer for the reason why.

For any particular TimeZone

TimeZone.getTimeZone( "US/Alaska").inDaylightTime( new Date() );
把回忆走一遍 2024-08-01 22:42:15

tl;dr

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

这是现代的 java .time(请参阅教程)版本的正确答案,作者:mamboking

示例代码:

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

请注意,在最后一行中,我们如何通过简单调用 ZonedDateTime 对象中提取 Instant 对象。 oracle.com/javase/8/docs/api/java/time/chrono/ChronoZonedDateTime.html#toInstant--" rel="noreferrer">toInstant

Java 中的日期时间类型表,包括现代的和传统的。


关于 java.time

java.time< /a> 框架内置于 Java 8 及更高版本中。 这些类取代了麻烦的旧遗留日期时间类,例如java.util.Date日历,& SimpleDateFormat

Joda-Time 项目,现已在 维护模式,建议迁移到 java.time 类。

要了解更多信息,请参阅 Oracle 教程 。 并在 Stack Overflow 上搜索许多示例和解释。 规范为 JSR 310

您可以直接与数据库交换java.time对象。 使用符合 JDBC 驱动程序 jeps/170" rel="noreferrer">JDBC 4.2 或更高版本。 不需要字符串,不需要 java.sql.* 类。

从哪里获取 java.time 类?

ThreeTen-Extra 项目通过附加类扩展了 java.time。 该项目是 java.time 未来可能添加的内容的试验场。 您可能会在这里找到一些有用的类,例如 Interval YearWeek YearQuarter ,以及更多

tl;dr

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

Here is the modern java.time (see Tutorial) version of the correct Answer by mamboking.

Example code:

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

Note how in the last line we had to extract an Instant object from our ZonedDateTime object with a simple call to toInstant.

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


About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.

Where to obtain the java.time classes?

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

断肠人 2024-08-01 22:42:15
TimeZone tz = TimeZone.getTimeZone("EST");
boolean inDs = tz.inDaylightTime(new Date());
TimeZone tz = TimeZone.getTimeZone("EST");
boolean inDs = tz.inDaylightTime(new Date());
空袭的梦i 2024-08-01 22:42:15

您将不得不使用这些坐标做更多的工作并找出它们所在的时区。一旦您知道是哪个时区, isDayLight() 方法就会很有用。

例如,您无法判断 -0500 是否为 EST(美国/加拿大东部标准时间)、CDT(美国/加拿大中部夏令时间)、COT(哥伦比亚时间)、AST(巴西阿克里标准时间)、ECT(厄瓜多尔)时间)等...

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

You're going to have to do a bit more work using those coordinates and figure out which time zone they're in. Once you know which TimeZone that is, the isDayLight() method would be useful.

For example, you have no way of telling whether -0500 is EST (US/Canada Eastern Standard Time), CDT (US/Canada Central Daylight Time), COT (Colombia Time), AST (Brazil Acre Standard Time), ECT (Ecuador Time), etc...

Some of these may or may not support daylight saving time.

绝情姑娘 2024-08-01 22:42:15

Joda Time 包含将为您计算偏移量的处理方法。 请参阅DateTimeZone.convertLocalToUTC(...)

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

Joda Time contains handling methods which will calculate the offsets for you. See DateTimeZone.convertLocalToUTC(...)

To supplement this, you will need to look up the current time zone with your latitude/longitude info. GeoNames provides a java client for its web service, as well as a simple web-request framework (i.e. http://ws.geonames.org/timezone?lat=47.01&lng=10.2)

德意的啸 2024-08-01 22:42:15
  1. 我不确定您将如何处理偏移量,但是 TimeZone 类的 getOffset() 方法将获取偏移量,而无需确定是否正在处理的时间是否处于夏令时 - 它会为您完成所有工作。 您甚至可以只使用 ZonedDateTime
  2. 有一个一个生成 IANA 时区边界 shapefile 的项目,它可以让您映射从纬度/经度到时区 ID。
  1. I'm not sure what you'd be doing with the offset, but the getOffset() method of the TimeZone class will get the offset, without having to find out whether the time being processed is in daylight saving time or not - it does all that work for you. You may even be able to just use the ZonedDateTime class.
  2. There is a project that generates a shapefile of IANA timezone boundaries, which might let you map from latitude/longitude to a timezone ID.
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文