How can I get the current date and time in UTC or GMT in Java?
To get the current date and time in UTC or GMT in Java, you can use the Instant class from the java.time package. The Instant class represents a single point in time in the ISO-8601 calendar system, with a resolution of nanoseconds.
To get the current date and time in UTC or GMT in Java, you can use the Instant class from the java.time package. The Instant class represents a single point in time in the ISO-8601 calendar system, with a resolution of nanoseconds.
Here is an example of how you can use the Instant class to get the current date and time in UTC or GMT in Java:
import java.time.Instant;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
public class CurrentDateTimeExample {
public static void main(String[] args) {
// Get the current date and time in UTC
Instant instant = Instant.now();
// Set the time zone to GMT
ZoneId zone = ZoneId.of("GMT");
// Format the date and time as a string
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
String dateTime = instant.atZone(zone).format(formatter);
System.out.println("Current date and time (GMT): " + dateTime);
}
}This example uses the now() method of the Instant class to get the current date and time in UTC, and then sets the time zone to GMT using the ZoneId class. Finally, it formats the Instant object into a readable string using the specified pattern. Note that Instant inherently represents UTC, so the ZoneId conversion is redundant for storage but fine for display purposes.