Java 程序将本地时间转换为 GMT
在本文中,我们将了解如何将本地时间转换为 GMT。Java 没有内置的 Date 类,但我们可以导入 java.time 包来使用日期和时间 API。该包包含许多日期和时间类。
以下是相同的演示 −
假设我们的输入是 −
The local time is: Fri Mar 18 00:01:54 IST 2022
所需的输出将是 −
The time in Gmt is: 17/03/2022 18:31:54
算法
Step 1 - START Step 2 - Declare an object of LocalDateTime namely date. Step 3 - Define the values. Step 4 - Define different date time formats using DateTimeFormatter objects. Step 5 - Display the GMT date time formats Step 6 - Stop
示例 1
在这里,我们在“main”函数下将所有操作绑定在一起。
import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; import java.util.TimeZone; public class Demo { public static void main(String[] args){ System.out.println("The required packages have been imported"); Date localTime = new Date(); System.out.println("A Date object is defined"); DateFormat GMT_format = new SimpleDateFormat("dd/MM/yyyy" + " " + " HH:mm:ss"); GMT_format.setTimeZone(TimeZone.getTimeZone("GMT")); System.out.println("\nThe local time is: " + localTime); System.out.println("The time in Gmt is: " + GMT_format.format(localTime)); } }
输出
The required packages have been imported A Date object is defined The local time is: Tue Mar 29 08:59:11 UTC 2022 The time in Gmt is: 29/03/2022 08:59:11
示例 2
在这里,我们将操作封装到表现出面向对象编程的函数中。
import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; import java.util.TimeZone; public class Demo { static void GMT_time(Date localTime){ DateFormat GMT_format = new SimpleDateFormat("dd/MM/yyyy" + " " + " HH:mm:ss"); GMT_format.setTimeZone(TimeZone.getTimeZone("GMT")); System.out.println("\nThe local time is: " + localTime); System.out.println("The time in Gmt is: " + GMT_format.format(localTime)); } public static void main(String[] args){ System.out.println("The required packages have been imported"); Date localTime = new Date(); System.out.println("A Date object is defined"); GMT_time(localTime); } }
输出
The required packages have been imported A Date object is defined The local time is: Tue Mar 29 08:59:38 UTC 2022 The time in Gmt is: 29/03/2022 08:59:38
广告