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".
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
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();
...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With