format as GMT/UTC time when default timezone is something else
I have a program which needs to run under my loca开发者_JAVA技巧l timezone for other reasons, but for one procedure i need to output dates using a SimpleDateFormat in GMT.
what is the tidiest way to do this?
Using the standard API:
Instant now = Instant.now();
String result = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.LONG)
.withZone(ZoneId.of("GMT"))
.format(now);
System.out.println(result);
The 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()));
Given that SimpleDateFormat
isn't thread-safe, I'd say that the tidiest way is to use Joda Time instead. Then you can create a single formatter (calling withZone(DateTimeZones.UTC)
to specify that you want UTC) and you're away:
private static DateTimeFormatter formatter = DateTimeFormat.forPattern(...)
.withZone(DateTimeZone.UTC);
...
String result = formatter.print(instant);
This has the other benefit that you can use Joda Time elsewhere in your code, which is always a good thing :)
精彩评论