java.time and ThreeTenABP
DateTimeFormatter jsonDateFormatter
= DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm:ss.SSSSSS");
DateTimeFormatter turkishDateFormatter
= DateTimeFormatter.ofPattern("EEEE MMM d", Locale.forLanguageTag("tr"));
ZoneId zone = ZoneId.of("Europe/Istanbul");
String dateFromJson = "2019-11-27 14:42:23.000000";
String timezoneTypeFromJson = "3";
String timezoneFromJson = "UTC";
if (! timezoneTypeFromJson.equals("3")) {
throw new IllegalStateException("This Stack Overflow answer only supports timezone_type 3");
}
LocalDateTime ldt = LocalDateTime.parse(dateFromJson, jsonDateFormatter);
ZoneId jsonZone = ZoneId.of(timezoneFromJson);
ZonedDateTime dateTime = ldt.atZone(jsonZone).withZoneSameInstant(zone);
ZonedDateTime futureDateTime = dateTime.plusMonths(4);
String wantedDateString = futureDateTime.format(turkishDateFormatter);
System.out.println(wantedDateString);
Output is the desired:
Cuma Mar 27
(Turkish for Friday Mar 27)
According to this answer timezone_type 3 really means a time zone ID in the form of region/city, for example Europe/London or Etc/UTC. UTC
is an alias to Etc/UTC
, so works too.
If you didn’t want the result in Istanbul time zone, just fill a different one into the code.
SimpleDateFormat
is notoriously troublesome and also cannot parse a date-time string with 6 decimals on the seconds (it only supports 3 decimals). It is also long outdated. Date
and Calendar
too are poorly designed and long outdated. Instead of those classes I am using java.time, the modern Java date and time API.
Or use a built-in localized format
You wanted your date printed with the day of week and with the year left out. For this purpose you need to hand specify the format as I do above. So mostly for other readers: for most purposes a built-in format is suitable and has two potential advantages: it fits the users’ expectations well and it lends itself well to internationalization. For example:
DateTimeFormatter turkishDateFormatter = DateTimeFormatter
.ofLocalizedDate(FormatStyle.LONG)
.withLocale(Locale.forLanguageTag("tr"));
27 Mart 2020 Cuma
Or shorter:
DateTimeFormatter turkishDateFormatter = DateTimeFormatter
.ofLocalizedDate(FormatStyle.MEDIUM)
.withLocale(Locale.forLanguageTag("tr"));
27.Mar.2020
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 use the Android edition of ThreeTen Backport. It’s called ThreeTenABP. And make sure you import the date and time classes from
org.threeten.bp
with subpackages.
Links