java.time
List<String> allDate_time = new ArrayList<>();
String date_time = "2018-03-18T01:39:45+01:00";
allDate_time.add( date_time );
for (String dateTimeString : allDate_time) {
OffsetDateTime odt = OffsetDateTime.parse(dateTimeString);
LocalDate date = odt.toLocalDate();
LocalTime timeOfDay = odt.toLocalTime();
System.out.println("Date: " + date + ". Time: " + timeOfDay + '.');
}
Output:
Date: 2018-03-18. Time: 01:39:45.
Since the OffsetDateTime
class of java.time
, the modern Java date and time API, parses your date-time strings without any explicit formatter, it would almost be a pity not to exploit this. The explanation why it’s so easy is that your string is in ISO 8601 format, and the classes of java.time
parse this format as their default.
If you you’re not sure whether the offset in the string (here +01:00
) agrees with your user’s time zone, convert to that time zone before extracting date and time. For example:
ZonedDateTime zdt = odt.atZoneSameInstant(ZoneId.of("America/Argentina/Cordoba"));
LocalDate date = zdt.toLocalDate();
LocalTime timeOfDay = zdt.toLocalTime();
With this change the output is:
Date: 2018-03-17. Time: 21:39:45.
My recommendations:
- Handle date and time as date and time objects using classes from the standard library. In the long run this is stabler and easier than relying on string manipulation and gives code that is much easier to read and maintain.
- Rather than the old classes
Date
and SimpleDateFormat
used in one other answer, use the modern ones in java.time
. Date
and SimpleDateFormat
are legacy, and SimpleDateFormat
in particular is notoriously troublesome.
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