Java 乔达时间夏令时

Java Joda time Daylight savings time

我在使用 JodaTime 处理夏令时时遇到困难。

 String time = "3:45-PM";   
 DateTimeFormatter formatter = DateTimeFormat.forPattern("KK:mm-a");
 DateTime dt = formatter.parseDateTime(time).withZone(DateTimeZone.forID("America/New_York"));
 dt = dt.toDateTime(DateTimeZone.UTC);

 startDate = startDate.withHourOfDay(dt.getHourOfDay()).withMinuteOfHour(dt.getMinuteOfHour());

此代码片段的输出最终为:

2015-04-08 16:46:51.952  INFO 12244 --- [nio-8080-exec-1] VALUES PULLED                        : 03:45-PM
2015-04-08 16:46:51.952  INFO 12244 --- [nio-8080-exec-1] VALUES PULLED                        : 08:45-PM

目前,时间是5小时。哪个不处理夏令时。如何让 Joda Time 将 DLS 考虑在内?

发生这种情况是因为解析后得到的 DateTime 对象设置为日期 01-01-1970。看起来您希望它会设置为今天,但事实并非如此。

如果您希望在时区 America/New_York 中将时间解释为今天下午 3:45,请执行以下操作:

String time = "3:45-PM";

DateTimeFormatter formatter = DateTimeFormat.forPattern("KK:mm-a")
        .withZone(DateTimeZone.forID("America/New_York"));

DateTime dt = formatter.parseDateTime(time)
        .withDate(LocalDate.now());

System.out.println(dt);

System.out.println(dt.withZone(DateTimeZone.UTC));

注意:您需要在DateTimeFormatter上设置区域。

java.time

下面引用的是 Home Page of Joda-Time:

的通知

Joda-Time is the de facto standard date and time library for Java prior to Java SE 8. Users are now asked to migrate to java.time (JSR-310).

解决方案使用java.time,现代API:

您需要结合当前日期和时间。

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;

public class Main {
    public static void main(String[] args) {
        String strTime = "3:45-PM";
        ZoneId zoneId = ZoneId.of("America/New_York");

        LocalTime time = LocalTime.parse(strTime, DateTimeFormatter.ofPattern("h:m-a", Locale.ENGLISH));
        LocalDate date = LocalDate.now(zoneId);
        LocalDateTime ldt = date.atTime(time);
        System.out.println(ldt);

        // Date-time at UTC
        System.out.println(ZonedDateTime.of(ldt, zoneId).toInstant());
    }
}

输出:

2021-05-08T15:45
2021-05-08T19:45:00Z

详细了解 modern date-time API* from Trail: Date Time


* 无论出于何种原因,如果您必须坚持Java 6 或Java 7,您可以使用ThreeTen-Backport which backports most of the java.time functionality to Java 6 & 7. If you are working for an Android project and your Android API level is still not compliant with Java-8, check Java 8+ APIs available through desugaring and