In this article, we will understand how to convert the local Time to GMT. Java does not have a built-in Date class, but we can import the java.time package to work with the date and time API. The package includes many date and time classes.
Below is a demonstration of the same −
Suppose our input is −
The local time is: Fri Mar 18 00:01:54 IST 2022
The desired output would be −
The time in Gmt is: 17/03/2022 18:31:54
Algorithm
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
Example 1
Here, we bind all the operations together under the ‘main’ function.
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));
}
}Output
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
Example 2
Here, we encapsulate the operations into functions exhibiting object-oriented programming.
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);
}
}Output
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