使用 inDaylightTime() 发出问题并确定日期是否处于夏令时

问题描述 投票:0回答:2

我一直在努力反对这个,不知道我在这里做错了什么。

我正在测试某个时区的 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));
    }    
}

当结果看起来很明显应该是“true”时,此代码不断打印“false”。

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

java timezone dst
2个回答
4
投票

您指定的时区为

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

如果您实际上指的是太平洋时间,则应指定

America/Los_Angeles
作为时区 ID。请记住,不同时区在一年中的不同时间在标准时和夏令时之间切换。

此外,

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


2
投票

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)…

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...

// 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
© www.soinside.com 2019 - 2024. All rights reserved.