java.time, ThreeTenABP and a built-in localized format
DateTimeFormatter formatter
= DateTimeFormatter.ofLocalizedDateTime(FormatStyle.SHORT)
.withLocale(Locale.US);
String startDate = "2019-02-18T06:30:38.9933333"; // Input String
LocalDateTime dateTime = LocalDateTime.parse(startDate);
System.out.println(dateTime.format(formatter));
Output:
2/18/19 6:30 AM
Still better than the above, get a LocalDateTime
from your database, or if this is not possible yet, then a Timestamp
that you convert like this:
LocalDateTime dateTime = DateTimeUtils.toLocalDateTime(timestampFromDatabase);
Or if using Java 8 or later:
LocalDateTime dateTime = timestampFromDatabase.toLocalDateTime();
The formatting is as before.
As a rule Java knows the best format for a particular audience better than you do. Using the built-in format also saves you from the error-prone task of writing a format pattern string.
In the first snippet I am exploiting the fact that your input string conforms with ISO 8601, the international standard format that the java.time classes parse (and also print) as their default, that is, without any explicit formatter.
The classes SimpleDateFormat
, java.util.Date
and java.sql.Date
are all poorly designed and long outdated. Instead I use java.time, the modern Java date and time API.
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 newer Android devices (from API level 26) 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; 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