Domanda

I generate an ISO datetime string (without time zone) like this:

val dateTime: LocalDateTime = LocalDateTime.now
val dateTimeStr: String = ISODateTimeFormat.dateTime.withZone(DateTimeZone.UTC).print(dateTime)

The code above produces the following string:

2014-04-10T06:13:19.283

Now I need to convert this string back to a LocalDateTime...

val dateTime = LocalDateTime.parse(dateTimeStr, ISODateTimeFormat.dateTime().withZone(DateTimeZone.UTC))

... and compare it with the current time:

val isBefore = dateTime.isBefore(LocalDateTime.now)

The code above doesn't work and produces the following error:

Invalid format: \"2014-04-27T17:51:06.780\" is too short

To fix the problem, I need to append a Z to dateTimeStr:

val dateTime = LocalDateTime.parse(s"${dateTimeStr}Z", ISODateTimeFormat.dateTime().withZone(DateTimeZone.UTC))

Is there a way to generate the ISO datetime string with the Z at the end?

È stato utile?

Soluzione

A LocalDateTime has NO timezone. So you cannot associate a timezone-aware format (Z stands for UTC timezone) with this zoneless data type.

If you insist on having Z-formats then you have to work with a global type like DateTime. So you have two different steps. One step is object conversion between local and global type:

LocalDateTime ldt = ...;
DateTime dt = ldt.toDateTime(DateTimeZone.UTC); // or another timezone

// reverse
DateTime dt = ...;
LocalDateTime ldt = dt.toLocalDateTime();

Second step is conversion between formatted string form and global timestamp:

LocalDateTime ldt = ...;
DateTime dt = ldt.toDateTime(DateTimeZone.UTC); // or another timezone
String iso = ISODateTimeFormat.dateTime().print(dt);

// reverse
String iso = ...; // with trailing Z or another timezone information
DateTime dt = IsoDateTimeFormat.parseDateTime(iso);
LocalDateTime ldt = dt.toLocalDateTime();

Finally you can combine these two steps for conversion between ISO-format with timezone information and a LocalDateTime as shown in the second step.

If you only need formatted strings without any timezone or offset information then you can stick the global type DateTime completely and just use localDateOptionalTimeParser() as @Sebastian has correctly mentioned.

Altri suggerimenti

Try to use

val dateTime: DateTime = DateTime.now

instead of

val dateTime: LocalDateTime = LocalDateTime.now

Or if you want to stick to LocalDateTime change the parsing:

val dateTime = LocalDateTime.parse(dateTimeStr)  // this uses the default localDateOptionalTimeParser
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top