Java程序:在其他时区显示当前时间


时区是指为了法律、商业和社会目的而采用统一标准时间的全球区域。假设您有一个同时在印度和日本运行的应用程序。在这里,您不能对这两个区域使用相同的时区。因此,必须在不同的时区显示时间。

Java提供了各种内置类,例如TimeZoneZoneId,以及诸如getTimeZone()之类的可以帮助在其他时区显示当前时间的方法。但是,在使用它们之前,必须将它们导入到您的Java程序中。


使用getTimeZone()和setTimeZone()方法

来自java.util包的TimeZone类提供了getTimeZone()方法,该方法接受时区ID作为字符串并返回给定ID的时区。获取时区后,使用其setTimeZone()方法设置Calendar对象的时区。然后,通过调用get()方法,您可以显示传入时区ID的当前时间。

示例

一个演示如何在其他时区显示当前时间的Java程序。

Open Compiler
import java.util.Calendar; import java.util.TimeZone; public class Demo { public static void main(String[] args) { Calendar cal = Calendar.getInstance(); System.out.println("Europe/Sofia TimeZone..."); cal.setTimeZone(TimeZone.getTimeZone("Europe/Sofia")); System.out.println("Hour = " + cal.get(Calendar.HOUR_OF_DAY)); System.out.println("Minute = " + cal.get(Calendar.MINUTE)); System.out.println("Second = " + cal.get(Calendar.SECOND)); System.out.println("Millisecond = " + cal.get(Calendar.MILLISECOND)); } }

执行此代码时,将显示以下输出:

Europe/Sofia TimeZone...
Hour = 11
Minute = 16
Second = 44
Millisecond = 354

使用ZonedDateTime和ZoneId类

在这种方法中,我们首先使用ZoneId.of()方法为指定的时区ID检索ZoneId对象。然后,使用ZonedDateTime.now()创建一个ZonedDateTime对象,该对象表示检索到的ZoneId对象的当前时间。执行这些步骤后,您可以使用getHour()getMinute()getSecond()方法来显示指定时区的当前时间。

示例

以下Java程序使用ZonedDateTime和ZoneId类显示其他时区的当前时间。

Open Compiler
import java.time.ZonedDateTime; import java.time.ZoneId; import java.time.format.DateTimeFormatter; public class Demo { public static void main(String[] args) { System.out.println("America/New_York TimeZone..."); ZonedDateTime current_time = ZonedDateTime.now(ZoneId.of("America/New_York")); System.out.println("Hour = " + current_time.getHour()); System.out.println("Minute = " + current_time.getMinute()); System.out.println("Second = " + current_time.getSecond()); } }

运行此代码后,您将获得以下结果:

America/New_York TimeZone...
Hour = 8
Minute = 4
Second = 57

Learn Java in-depth with real-world projects through our Java certification course. Enroll and become a certified expert to boost your career.

使用LocalTime和ZoneId类

这是显示其他时区当前时间的另一种方法。在这里,我们使用ZoneId.of()方法获取时区,并通过将此时区作为参数值传递给LocalTime.now()方法,我们检索该时区的当前时间。

示例

在这个Java程序中,我们使用LocalTime和ZoneId类来显示其他时区的当前时间。

Open Compiler
import java.time.LocalTime; import java.time.ZoneId; import java.time.format.DateTimeFormatter; public class Demo { public static void main(String[] args) { System.out.println("Asia/Tokyo TimeZone..."); LocalTime current_time = LocalTime.now(ZoneId.of("Asia/Tokyo")); System.out.println("Hour = " + current_time.getHour()); System.out.println("Minute = " + current_time.getMinute()); System.out.println("Second = " + current_time.getSecond()); } }

以上代码将生成以下结果:

Asia/Tokyo TimeZone...
Hour = 21
Minute = 6
Second = 43

更新于:2024年9月30日

903 次浏览

开启您的职业生涯

完成课程获得认证

开始学习
广告