Strange String Format for Date

LHA :

Java application gets a stream of JSON messages, within those, the String fields, that represent some date are formatted like \"2019-01-01+01:00\".

It looks like a normal date, followed by the timezone-offset, this guess of mine has been confirmed on the producer side.

Problem: Even though I still do not really get the logic behind it, I have to parse it in my Java App. The simplest approach would be to split that string on the '+' character and just parse the date part with some pattern in LocalDate.

But out of curiosity, maybe there is some Date format in Java I do not know of, which could allow for this strange string format?

Ole V.V. :

Yes there is. DateTimeFormatter.ISO_OFFSET_DATE. I agree that it’s weird, and I don’t know what use you should have of the offset. But you can parse into a LocalDate using the formatter:

    String stringFromJson = "2019-01-01+01:00";
    LocalDate date = LocalDate.parse(stringFromJson, DateTimeFormatter.ISO_OFFSET_DATE);
    System.out.println(date);

Output:

2019-01-01

Splitting at the + (plus sign) will not always work. A date with an offset may also come with a negative offset, for example -04:00, and with offset Z (for zero, that is, UTC). Of course you could write code to handle each of those situations manually, but it’s better to use the built-in formatter.

Don’t use Date and SimpleDateFormat. Those classes are poorly designed and long outdated, the latter in particular notoriously troublesome. Use LocalDate and DateTimeFormatter, both from java.time, the modern Java date and time API.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related