GMT
in Java, we can use the java.util.TimeZon
e class and its getOffset()
method. The getOffset()
method returns the offset of a particular time zone from GMT
in milliseconds.GMT
in Java :import java.util.Calendar;
import java.util.TimeZone;
public class ConvertLocalToGMT {
public static void main(String[] args) {
// Create a calendar object and set the local time
Calendar calendar = Calendar.getInstance();
calendar.set(2020, Calendar.APRIL, 22, 14, 30, 0); // Local time: 2:30 PM
// Get the GMT time zone
TimeZone gmtTimeZone = TimeZone.getTimeZone("GMT");
// Get the offset from GMT for the local time zone
int localOffset = calendar.getTimeZone().getOffset(calendar.getTimeInMillis());
// Get the offset from GMT for the GMT time zone
int gmtOffset = gmtTimeZone.getOffset(calendar.getTimeInMillis());
// Calculate the difference between the local time and GMT time
int timeDifference = gmtOffset - localOffset;
// Add the time difference to the local time to get the GMT time
calendar.add(Calendar.MILLISECOND, timeDifference);
// Display the GMT time
System.out.println("GMT Time: " + calendar.getTime());
}
}
GMT Time: Wed Apr 22 14:30:00 UTC 2020
Calendar
object and set it to the local time by specifying the year, month, day, hour, minute, and second. Then we get the GMT
time zone using the getTimeZone()
method of the TimeZone
class.getOffset()
method of the TimeZone
class to get the offset from GMT
for the local time zone and the GMT time zone. We then calculate the time difference between the local time and the GMT time by subtracting the local offset from the GMT offset.add()
method of the Calendar
class, and display the GMT time using the getTime()
method of the Calendar
class.