Home > Mobile >  How do I format this date
How do I format this date

Time:06-11

I am trying to parse the date which is in the format 2021-01-15T19:00:00 0000. I am not sure which format it is but based on my research I tried with methods below

1. val odt = OffsetDateTime.parse("2021-01-15T19:00:00 0000")
2. val zdt = ZonedDateTime.parse("2021-01-15T19:00:00 0000")

It is logging the exception:

java.time.format.DateTimeParseException: Text '2021-01-15T19:00:00 0000' could not be parsed at index 19
        at java.time.format.DateTimeFormatter.parseResolved0(DateTimeFormatter.java:1949)
        at java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1851)
        at java.time.ZonedDateTime.parse(ZonedDateTime.java:591)
        at java.time.ZonedDateTime.parse(ZonedDateTime.java:576)

CodePudding user response:

I would recommend to use the OffsetDateTime with the right offset - that should do the trick!

Best Regards!

CodePudding user response:

tl;dr

OffsetDateTime
.parse( 
    "2021-01-15T19:00:00 0000" , 
    DateTimeFormatter.ofPattern( "uuuu-MM-dd'T'HH:mm:ssxxxx" ) 
)
.toString()

2021-01-15T19:00Z

OffsetDateTime

Your input has an offset of zero hours-minutes-seconds from UTC, the 0000 portion.

So you should be parsing with OffsetDateTime rather than ZonedDateTime.

ZonedDateTime

The ZonedDateTime class is for a time zone rather than an offset. A time zone is the named history of the past, present, and future changes to the offset used by the people of a particular region, as decided by their politicians. Time zones have a name in format of Continent/Region such as Europe/Paris or America/Edmonton.

Optional COLON in offset

Unfortunately, your input omitted the COLON character from between the hours and minutes of the offset. While optional in the ISO 8601 standard, the parse method expects to find that character.

If you know all the inputs have the same 0000 I would simply perform a string manipulation.

OffsetDateTime odt = OffsetDateTime.parse( "2021-01-15T19:00:00 0000".replace( " 0000" , " 00:00" ) ) ;

If some other offsets might appear, you must specify a formatting pattern.

DateTimeFormatter f = DateTimeFormatter.ofPattern( "uuuu-MM-dd'T'HH:mm:ssxxxx" ) ;
OffsetDateTime odt = OffsetDateTime.parse( input , f ) ;

See this code run live at Ideone.com.

2021-01-15T19:00Z

  • Related