shrek_23
shrek_23

Reputation: 51

Date time format pattern for ISO_OFFSET_DATE_TIME

I'm after the date time format pattern for ISO_OFFSET_DATE_TIME

2019-09-30T10:05:16+10:00

yyyy-MM-dd'T'HH:mm:ssZ is valid for 2019-09-30T10:05:16+1000 but I need the colon in the zone offset

If this is not possible, I'll need a regular expression.

Upvotes: 1

Views: 6586

Answers (3)

apphitect
apphitect

Reputation: 256

You can also format it with SimpleDateFormat. DateTimeFormatter requires Android API Level 26+, SimpleDateFormat with "X" pattern can use with Android API Level 24+.

val dateString = "2019-09-30T10:05:16+10:00"
val readFormat = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX")
val date = readFormat.parse(dateString) // You will get Date(2019-09-30 00:05:16) in UTC.

Upvotes: 1

Anonymous
Anonymous

Reputation: 86399

It depends. DateTimeFormatter.ISO_OFFSET_DATE_TIME prints and parses strings with and without seconds and with and without fraction of second, the latter up to 9 decimals.

If you only need the pattern for the variant of the format given in your question, with seconds and without fraction of second, the answer by MC Emperor is exactly what you need.

If you need the full flexibility of ISO_OFFSET_DATE_TIME, then there is no pattern that can give you that. Then you will need to go the regular expression way. Which in turn can hardly give you as strict a validation as the formatter. And the regular expression may still grow complicated and very hard to read.

Link: My answer to a similar question with a few more details.

Upvotes: 2

MC Emperor
MC Emperor

Reputation: 23057

You need uuuu-MM-dd'T'HH:mm:ssXXX here.

String str = "2019-09-30T10:05:16+10:00";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("uuuu-MM-dd'T'HH:mm:ssXXX");
OffsetDateTime datetime = OffsetDateTime.parse(str, formatter);
System.out.println(datetime);

Upvotes: 5

Related Questions