Format like GMT / UTC, when the default time zone is something else

I have a program that should run in my local time zone for other reasons, but for one procedure, I need to output dates using SimpleDateFormat in GMT.

What is the easiest way to do this?

+6
java date timezone
source share
2 answers

Using the standard API :

Instant now = Instant.now(); String result = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.LONG) .withZone(ZoneId.of("GMT")) .format(now); System.out.println(result); 

New DateTimeFormatter instances are immutable and can be used as static variables.

Using the old standard API:

 TimeZone gmt = TimeZone.getTimeZone("GMT"); DateFormat formatter = DateFormat.getTimeInstance(DateFormat.LONG); formatter.setTimeZone(gmt); System.out.println(formatter.format(new Date())); 
+10
source share

Given that SimpleDateFormat not thread safe, I would say the easiest way is to use Joda Time . Then you can create one formatter (calling withZone(DateTimeZones.UTC) to indicate that you want UTC), and you are absent:

 private static DateTimeFormatter formatter = DateTimeFormat.forPattern(...) .withZone(DateTimeZone.UTC); ... String result = formatter.print(instant); 

This has another advantage that you can use Joda Time elsewhere in your code, which is always good :)

+8
source share

All Articles