Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java time format for time zone

I am trying to get output for a date in the format (String):

20170801​ ​123030​ ​America/Los_Angeles

But using this code:

SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd hhmmss Z", Locale.US);
sdf.setTimeZone(TimeZone.getTimeZone("America/Los_Angeles"));
System.out.println(sdf.format(new java.util.Date()));

I am getting the output as (notice the zone part):

20174904 024908 -0700

Any idea how to fix it? I need to print "​America/Los_Angeles" instead of "-0700".

like image 641
VictorGram Avatar asked Jul 22 '26 04:07

VictorGram


2 Answers

Looks like the SimpleDateFormat doesn't support what you want.

Here are possible formats:

z   Time zone   General time zone   Pacific Standard Time; PST; GMT-08:00  
Z   Time zone   RFC 822 time zone   -0800  
X   Time zone   ISO 8601 time zone  -08; -0800; -08:00  

You can just add "America/Los_Angeles" after a formatted date:

TimeZone timeZone = TimeZone.getTimeZone("America/Los_Angeles");
DateFormat sdf = new SimpleDateFormat("yyyyMMdd hhmmss", Locale.US);
sdf.setTimeZone(timeZone);
System.out.println(sdf.format(new Date()) + " " + timeZone.getID());

DateFormat sdfWithTimeZone = new SimpleDateFormat("yyyyMMdd hhmmss zzzz", Locale.US);
sdfWithTimeZone.setTimeZone(timeZone);
System.out.println(sdfWithTimeZone.format(new Date()));

Output:

20171004 031611 America/Los_Angeles
20171004 031611 Pacific Daylight Time
like image 101
Alexandr Lihonosov Avatar answered Jul 23 '26 19:07

Alexandr Lihonosov


If you can use Java 8, you can use DateTimeFormatter and its symbol V to display the Zone ID:

Instant now = Instant.now();
DateTimeFormatter fmt = DateTimeFormatter.ofPattern("yyyyMMdd hhmmss VV")
    .withLocale(Locale.US)
    .withZone(ZoneId.of("America/Los_Angeles"));
System.out.println(fmt.format(now));

Prints:

20171004 032552 America/Los_Angeles

Note that SimpleDateFormat doesn't support this flag as mentioned in Alexandr's answer.

If you have to start from java.util.Date but can use Java 8 still, you can convert it to an Instant first:

Instant now = new java.util.Date().toInstant();
...
like image 31
Jens Hoffmann Avatar answered Jul 23 '26 21:07

Jens Hoffmann