Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

format as GMT/UTC time when default timezone is something else

I have a program which needs to run under my local 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?

like image 281
pstanton Avatar asked Jan 18 '10 22:01

pstanton


1 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);

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()));
like image 114
McDowell Avatar answered Sep 20 '22 12:09

McDowell