java.time
String[] exampleStrings = {
"2018-09-10T10:35:00.377Z",
"2018-09-10T10:35:00.12Z",
"2018-09-10"
};
for (String example : exampleStrings) {
if (example.contains("T")) {
OffsetDateTime dateTime = OffsetDateTime.parse(example);
System.out.println("Date: " + dateTime.toLocalDate()
+ " Time: " + dateTime.toLocalTime()
+ " Offset: " + dateTime.getOffset());
} else {
LocalDate date = LocalDate.parse(example);
System.out.println("Date: " + date);
}
}
Your formats are allowed variants of ISO 8601. java.time, the modern Java date and time API, parses these formats without any explicit formatter. The first two example strings have date and time and the characteristic T
to separate them, and an offset from UTC (Z
means offset 0). The third has only a date. So test whether the string has the T
in it and use the corresponding java.time class for the rest.
Output from the above snippet is:
Date: 2018-09-10 Time: 10:35:00.377 Offset: Z
Date: 2018-09-10 Time: 10:35:00.120 Offset: Z
Date: 2018-09-10
I don’t know how you will handle the two different types OffsetDateTime
and LocalDate
in the rest of your code. If you don’t need the time part, just the date, use dateTime.toLocalDate()
to get a LocalDate
and just pass this type on in all cases. Since you do need the time part, you may, depending on your situation and requirements, get away with the opposite conversion: in the date case you may get an OffsetDateTime
from for example date.atStartOfDay().atOffset(ZoneOffset.UTC)
, but please do check whether this gives you an appropriate time.
I do agree with the now deleted answer by Khemraj, though, that your server ought to be able to deliver one consistent format or at least indicate which format it is giving you.
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, I’m told) the modern API comes built-in.
- In Java 6 and 7 get the ThreeTen Backport, the backport of the new 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