Your code is implicitly using the JVM’s default time zone. This doesn’t seem to give you the result that you wanted. The solution is to specify time zone explicitly (which is usually a good idea anyway).
java.time
I am using java.time, the modern Java date and time API.
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm:ss");
ZoneId usersDesiredTimeZone = ZoneId.of("Africa/Tripoli");
ZonedDateTime now = ZonedDateTime.now(usersDesiredTimeZone);
String text = now.format(formatter);
System.out.println(text);
When I ran this snippet just now, the output was:
2020-09-02 16:51:21
The time printed is 2 hours ahead of UTC because this is what Libya is using. Please substitute your own desired time zone.
Yet another change from your code is I am using uppercase HH
for hour of day from 00 through 23 in the format pattern string. Lowercase hh
is for hour within AM or PM from 01 through 12. I figured this was probably not what you had wanted.
Question: Doesn’t java.time require Android API level 26?
java.time works nicely on both older and newer Android devices. It just requires at least Java 6.
- In Java 8 and later and on newer Android devices (from API level 26) the modern API comes built-in.
- In non-Android Java 6 and 7 get the ThreeTen Backport, the backport of the modern classes (ThreeTen for JSR 310; see the links at the bottom).
- On older Android either use desugaring or the Android edition of ThreeTen Backport. It’s called ThreeTenABP. In the latter case make sure you import the date and time classes from
org.threeten.bp
with subpackages.
Links