在Java 8中获取当前时间 [英] Getting current time in Java 8
问题描述
我正在探索Java 8的新java.time API。我特别想检索当前时间(我当前的时区,不同的时区和不同的偏移量)。
I am exploring the new java.time API of Java 8. I am particularly trying to retrieve the current time (my current time zone, of a different time zone, and of a different offset).
代码是:
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);
}
但是,当我调用这些方法时,我会获得相同的时间(我的系统时间),这显然不是我所期待的。
But, when I call the methods I get the same time-of-day (my system time), which is obviously not what I am expecting.
方法的输出调用:
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
即使设置了不同的时区和偏移量,为什么我会得到相同的时间?
Even after setting a different time zone and offset, why am I getting the same time?
推荐答案
LocalDateTime.now()
始终返回默认时区的当前日期/时间(例如10月13日) @ 11.20am在伦敦)。当您使用特定的 ZoneId $ c $创建
ZonedDateTime
或 OffsetTime
时c>或 ZoneOffset
,你得到相同的日期和时间但是在不同的时区(例如洛杉矶的10月13日上午11点20分),这代表了不同的瞬间时间。
LocalDateTime.now()
always returns the current date/time in your default timezone (say 13 October @ 11.20am in London). When you create a ZonedDateTime
or OffsetTime
from it with a specific ZoneId
or ZoneOffset
, you get the same date and time but in a different time zone (for example 13 october at 11.20am in Los Angeles), which represents a different instant in time.
你可能正在寻找类似的东西:
You are probably looking for something like:
Instant now = Instant.now();
ZoneId zoneId = ZoneId.of("America/Los_Angeles");
ZonedDateTime dateAndTimeInLA = ZonedDateTime.ofInstant(now, zoneId);
这将计算洛杉矶的当前日期和时间:10月13日,3:20am。
This will calculate the current date and time in Los Angeles: 13 october, 3.20am.
这篇关于在Java 8中获取当前时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!