java - 在 Java 8 中获取不同时区的当前时间

标签 java java-8 java-time

我正在探索 Java 8 的新 java.time API。我特别尝试检索当前时间(我的当前时区、不同时区和不同偏移量)。

代码是:

public static void getCurrentLocalTime(){
    LocalTime time = LocalTime.now();
    System.out.println("Local Time Zone: "+ZoneId.systemDefault().toString());
    System.out.println("Current local time : " + time);
}

public static void getCurrentTimeWithTimeZone(){
    LocalDateTime localtDateAndTime = LocalDateTime.now();
    ZoneId zoneId = ZoneId.of("America/Los_Angeles");
    ZonedDateTime dateAndTimeInLA  = ZonedDateTime.of(localtDateAndTime, zoneId);
    String currentTimewithTimeZone =dateAndTimeInLA.getHour()+":"+dateAndTimeInLA.getMinute();
    System.out.println("Current time in Los Angeles: " + currentTimewithTimeZone);
}

public static void getCurrentTimeWithZoneOffset(){
    LocalTime localtTime = LocalTime.now();
    ZoneOffset offset = ZoneOffset.of("-08:00");
    OffsetTime  offsetTime  = OffsetTime.of(localtTime, offset);
    String currentTimewithZoneOffset =offsetTime.getHour()+":"+offsetTime.getMinute();
    System.out.println("Current time  with offset -08:00: " + currentTimewithZoneOffset);
}

但是,当我调用这些方法时,我得到了相同的一天中的时间(我的系统时间),这显然不是我所期望的。

方法调用的输出:

Current time in Los Angeles: 19:59
Local Time Zone: Asia/Calcutta
Current local time : 19:59:20.477
Current time  with offset -08:00: 19:59

即使设置了不同的时区和偏移量,为什么我得到的时间是相同的?

最佳答案

LocalDateTime.now() 总是返回默认时区的当前日期/时间(例如伦敦的 10 月 13 日上午 11 点 20 分)。当您使用特定的 ZoneIdZoneOffset 从中创建 ZonedDateTimeOffsetTime 时,您会得到相同的日期和时间,但在不同的时区(例如洛杉矶的 10 月 13 日上午 11 点 20 分),这代表不同的时刻。

您可能正在寻找类似的东西:

Instant now = Instant.now();
ZoneId zoneId = ZoneId.of("America/Los_Angeles");
ZonedDateTime dateAndTimeInLA = ZonedDateTime.ofInstant(now, zoneId);

这将计算洛杉矶的当前日期和时间:10 月 13 日凌晨 3 点 20 分。

关于java - 在 Java 8 中获取不同时区的当前时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33100130/

相关文章:

java - 为什么 OffsetDateTime 不能在 Java 8 中解析 '2016-08-24T18:38:05.507+0000'

java - 解析具有冲突区域 ID 和偏移量的字符串时 ZonedDateTime 的行为

java - 使用 LookAR 的增强现实示例

java - HashMap 的优先级队列

Java 8 流 : Populating a list of objects instantiated using values in a HashMap

Java 8 使用 2 个字段进行排序

美国日历的 Java Week to Date 转换(非 ISO8601)

java - 为什么不能在赋值运算符中递增变量?

java - CVS已启用,但Intellij找不到它

java - Dropwizard 指标注释 @Timed 不工作