moyo
moyo

Reputation: 1402

ThreeTenABP: DateTimeParseException

Trying to change date formats of a String but getting DateTimeException:

String oldDate = "2018-12-18T17:04:56+00:00";
String outputFormat = "DD-MM";
try {
    Instant instant = Instant.parse(oldDate);
    LocalDateTime localDateTime = instant.atZone(ZoneId.systemDefault()).toLocalDateTime();
    return localDateTime.format(DateTimeFormatter.ofPattern(outputFormat);
} catch (DateTimeException | IllegalArgumentException e) {
    Log.e("Error", e.getLocalizedMessage());
    return "";
}

Error I am getting is: Text '2018-12-18T17:04:56+00:00' could not be parsed at index 19

I'm using com.jakewharton.threetenabp:threetenabp:1.1.1 since I cannot use Java 8 classes

Upvotes: 1

Views: 1297

Answers (1)

Basil Bourque
Basil Bourque

Reputation: 339422

tl;dr

OffsetDateTime.parse(                // Represent a moment, a date with time-of-day in the context of an offset-from-UTC (some number of hours-minutes-seconds).
    "2018-12-18T17:04:56+00:00"      // Input string in standard ISO 8601 format, with an indicator of an offset-from-UTC of zero hours and zero minutes, meaning UTC itself.
)                                    // Returns an `OffsetDateTime` object.
.atZoneSameInstant(                  // Adjust our moment from UTC to the wall-clock time used by the people of a particular region (a time zone).
    ZoneId.systemDefault()           // Using the JVM’s current default time zone. NOTE: this default can change at any moment during runtime. If important, confirm with the user.
)                                    // Returns a `ZonedDateTime` object.
.toString()                          // Generate text in standard ISO 8601 format wisely extended by appending the name of the zone in square brackets. Returns a `String` object.

2018-12-18T09:04:56-08:00[America/Los_Angeles]

Details

Here is example Java code using ThreeTen-Backport project, which is extended by ThreeTenABP for pre-26 Android.

import org.threeten.bp.*;

Wrong formatter

The Instant.parse command uses the DateTimeFormatter.ISO_INSTANT formatter. That formatter expects a Z on the end to indicate UTC.

The Instant class is the basic building-block class of java.time framework. For more flexibility, use the OffsetDateTime. Its default formatter DateTimeFormatter.ISO_OFFSET_DATE_TIME can handle your input.

String input = "2018-12-18T17:04:56+00:00";
OffsetDateTime odt = OffsetDateTime.parse( input );

odt.toString(): 2018-12-18T17:04:56Z

Wrong class

Do not use LocalDateTime for tracking a moment. That class purposely lacks any concept of time zone or offset-from-UTC. It is simply a date and a time-of-day. As such, it cannot represent a moment, is never a point on the timeline. Instead, this class represents potential moments along a range of 26-27 hours, the range of time zones around the globe.

To track a moment, use only:

  • Instant
    A moment in UTC, always UTC.
  • OffsetDateTime
    A date, a time-of-day, with an offset-from-UTC. An offset is merely a number of hours-minutes-seconds, nothing more.
  • ZonedDateTime
    A moment as seen through the wall-clock time used by the people of a particular region, a time zone. A zone is a history of the past, present, and future changes to the offset used in a particular region.

To adjust our OffsetDateTime from UTC to some time zone, apply a ZoneId to get a ZonedDateTime.

ZoneId z = ZoneId.systemDefault() ;  // If important, confirm the zone with user rather than depending on the JVM’s current default zone.
ZonedDateTime zdt = odt.atZoneSameInstant( z ) ;

zdt.toString(): 2018-12-18T09:04:56-08:00[America/Los_Angeles]

With these results, we see that 5 PM in UTC is simultaneously 9 AM on most of the west coast of North America. The difference of -08:00 means on this date, the west coast was eight hours behind UTC.


About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.

Where to obtain the java.time classes?

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

Upvotes: 3

Related Questions