0

一直在反对这一点,并且不确定我在这里做错了什么。

我正在测试某个时区的 inDaylightTime() 方法,但在这种情况下它应该返回“true”时返回“false”。

import java.util.TimeZone;
import java.util.Date;

public class TimeZoneDemo {
    public static void main( String args[] ){

        Date date = new Date(1380931200); // Sat, 05 Oct 2013, within daylight savings time.

        System.out.println("In daylight saving time: " + TimeZone.getTimeZone("GMT-8:00").inDaylightTime(date));
    }    
}

当结果似乎很明显应该为“真”时,此代码会继续打印“假”。

我在这里想念什么?将不胜感激任何指导。

4

2 回答 2

4

您指定的时区GMT-8:00- 这是一个固定时区,比 UTC永久落后 8 小时。它不遵守夏令时。

如果您实际上是指太平洋时间,则应指定America/Los_Angeles为时区 ID。请记住,不同时区在一年中的不同时间在标准时间和夏令时之间切换。

此外,new Date(1380931200)实际上是在 1970 年 1 月 - 你的意思是new Date(1380931200000L)- 不要忘记这个数字是自 Unix 纪元以来的毫秒数,而不是seconds

于 2013-11-08T16:36:32.533 回答
1

Jon Skeet 的回答是正确的。

在乔达时代

只是为了好玩,下面是使用 Java 7 中的第三方库Joda-Time 2.3 的源代码解决方案。

细节

DateTimeZone类有一个方法isStandardOffset。唯一的技巧是该方法需要很长时间,支持 DateTime 实例的毫秒数,通过调用DateTime类的“超类”(BaseDateTime)方法getMillis来访问。

示例源代码

// © 2013 Basil Bourque. This source code may be used freely forever by anyone taking full responsibility for doing so.

org.joda.time.DateTimeZone losAngelesTimeZone = org.joda.time.DateTimeZone.forID("America/Los_Angeles");
org.joda.time.DateTime theSecondAt6PM = new org.joda.time.DateTime( 2013, 11, 2, 18, 0, losAngelesTimeZone ) ;
org.joda.time.DateTime theThirdAt6PM = new org.joda.time.DateTime( 2013, 11, 3, 18, 0, losAngelesTimeZone ) ; // Day when DST ends.

System.out.println("This datetime 'theSecondAt6PM': " + theSecondAt6PM + " is in DST: " + losAngelesTimeZone.isStandardOffset(theSecondAt6PM.getMillis()));
System.out.println("This datetime 'theThirdAt6PM': " + theThirdAt6PM + " is in DST: " + losAngelesTimeZone.isStandardOffset(theThirdAt6PM.getMillis()));

运行时,请注意与 UTC 的偏移量差异(-7 与 -8)……</p>

This datetime 'theSecondAt6PM': 2013-11-02T18:00:00.000-07:00 is in DST: false
This datetime 'theThirdAt6PM': 2013-11-03T18:00:00.000-08:00 is in DST: true

关于 Joda-Time……</p>

// Joda-Time - The popular alternative to Sun/Oracle's notoriously bad date, time, and calendar classes bundled with Java 7 and earlier.
// http://www.joda.org/joda-time/

// Joda-Time will become outmoded by the JSR 310 Date and Time API introduced in Java 8.
// JSR 310 was inspired by Joda-Time but is not directly based on it.
// http://jcp.org/en/jsr/detail?id=310

// By default, Joda-Time produces strings in the standard ISO 8601 format.
// https://en.wikipedia.org/wiki/ISO_8601

// About Daylight Saving Time (DST): https://en.wikipedia.org/wiki/Daylight_saving_time

// Time Zone list: http://joda-time.sourceforge.net/timezones.html
于 2013-11-08T23:10:10.317 回答