在 Java 中将 EST 转换为 EDT 或反之亦然

2022-01-11 00:00:00 timezone calendar java

谁能说说三件事:

  1. 如何从 java.util.Date 实例中获取 TimeZone?
  2. 如何知道夏令时是否适用?
    我想我可以通过 timeZone.getDSTSavings 知道,但我面临的问题是,即使我将系统的日期设为 2012 年 2 月 1 日,我仍然是将值设为正数(我猜是 3600000)
  3. 如何将 EST 时间转换为 EDT,反之亦然?

推荐答案

如何从 java.util.Date 实例中检索 TimeZone?

How to retrieve TimeZone from java.util.Date instance?

没有这样的事情.Date just 表示自 Unix 纪元(UTC 时间 1970 年 1 月 1 日午夜)以来的毫秒数.它与特定的日历系统或时区无关.换句话说,如果我和一个朋友一起打电话(零延迟;)并且我点击我的手指,我们都会同意该点击的 Date -即使我使用公历而他使用儒略历,即使我在伦敦而他在纽约.这是相同的即时.

There's no such thing. A Date just represents a number of milliseconds since the Unix epoch, which was midnight on January 1st 1970 UTC. It's not associated with a particular calendar system or time zone. To put it another way, if a friend and I are on the phone together (with a zero latency ;) and I click my fingers, we would both agree on the Date at which that click too place - even if I'm using the Gregorian calendar and he's using the Julian calendar, and even if I'm in London and he's in New York. It's the same instant in time.

如何知道夏令时是否适用?,我想我可以通过 timeZone.getDSTSavings 知道,但我面临的问题是,即使我将系统的日期设为 2012 年 2 月 1 日,我仍然可以获得价值为正(我猜是 3600000)

How to know whether Daylight savings is applicable?, I suppose I can know it by doing timeZone.getDSTSavings, but problem I am facing is that even if I make my system's date as Feb 1 2012, still I am getting the value as positive (I guess 3600000)

理想情况下,使用 Joda Time 而不是 java.util.Date/Calendar/TimeZone,但在 TimeZone 内您可以使用 TimeZone.getOffset(long) 查找与 UTC 的偏移量,或 TimeZone.inDaylightTime(Date) 只给你一个是/否的答案.

Ideally, use Joda Time instead of java.util.Date/Calendar/TimeZone, but within TimeZone you can use TimeZone.getOffset(long) to find the offset from UTC, or TimeZone.inDaylightTime(Date) to just give you a yes/no answer.

如何将 EST 时间转换为 EDT,反之亦然?

How to convert EST time to EDT or vice versa?

通常这是一个无效的问题 - 因为在任何一个时间实例中, EST 或 EDT 适用.您通常会从一个时区转换到另一个时区,并且EDT"和EST"不是不同的时区——它们是相同时区内的不同偏移量.您要求这样做的事实表明您可能一开始就错误地对数据进行了建模(不幸的是,这对于日期/时间值很容易做到).请向我们提供更多信息,我们或许可以为您提供更多帮助.

Usually that's an invalid question - because at any one instance in time, either EST or EDT applies. You normally convert from one time zone to another, and "EDT" and "EST" aren't different time zones - they're different offsets within the same time zone. The fact that you're asking for this suggests that you may be modelling your data incorrectly to start with (which is unfortunately easy to do with date/time values). Please give us more information and we may be able to help you more.

相关文章