Two messages:
- Your expectations are wrong. A
Date
hasn’t got a time zone, it cannot have. So what you are trying to obtain is impossible usingDate
andSimpleDateFormat
no matter how you write the code. - The classes
Date
,SimpleDateFormat
andTimeZone
are long outdated and poorly designed. Their modern replacements are in java.time, the date and time API introduced in 2014.
ZonedDateTime
A modern ZonedDateTime
has a time zone as the name says:
DateTimeFormatter formatter
= DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss z", Locale.US);
ZonedDateTime nowInHawaii = ZonedDateTime.now(ZoneId.of("Pacific/Honolulu"));
String dateS = nowInHawaii.format(formatter);
System.out.println(dateS);
Output from this snippet was:
2018/09/24 18:43:19 HST
If you want the offset in the output, change the formatter thusly:
DateTimeFormatter formatter
= DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss OOOO", Locale.US);
2018/09/24 18:45:53 GMT-10:00
Question: Can I use java.time
on Android?
Yes, java.time
works nicely on older and newer Android devices. It just requires at least Java 6.
- In Java 8 and later and on new Android devices (from API level 26, I’m told) the modern API comes built-in.
- In Java 6 and 7 get the ThreeTen Backport, the backport of the modern classes (ThreeTen for JSR 310, where the modern API was first described).
- On (older) Android, use the Android edition of ThreeTen Backport. It’s called ThreeTenABP. Make sure you import the date and time classes from package
org.threeten.bp
and subpackages.
Links
- Oracle tutorial: Date Time, explaining how to use
java.time
. - ThreeTen Backport project
- ThreeTenABP, Android edition of ThreeTen Backport
- Question: How to use ThreeTenABP in Android Project, with a very thorough explanation.
- Java Specification Request (JSR) 310.