Home > Enterprise >  Parse an old date in JAVA
Parse an old date in JAVA

Time:08-18

I'm trying to parse "1901-01-01T00:20:40.000 02:20:40" date but I'm getting the following error:

Cannot deserialize value of type java.util.Date from String "1901-01-01T00:20:40.000 02:20:40": not a valid representation (error: Failed to parse Date value '1901-01-01T00:20:40.000 02:20:40': Cannot parse date "1901-01-01T00:20:40.000 02:20:40":

I read it is a problem with java date format which is not able the pare old dates, is there something that I can do in order to fix this issue?

---- edit ----

until now, i deserialized lots of different dates from the last 20 years, and they all worked fine. It is a very simple object:

public class Record extends Docs {
    public Date published;
}

and

    results =
            given().
                    config(config).
                    log().ifValidationFails().
                    when().
                    get(lastUrlComponent).
                    then().
                    log().ifValidationFails().
                    statusCode(HttpStatus.SC_OK).
                    contentType(ContentType.JSON).
                    assertThat().body(matchesJsonSchemaInClasspath(jsonSchemaInClasspath)).
                    extract().
                    response().as(resultsClass);
}

CodePudding user response:

It should follow steps bellow:

  1. Read it as String (It can work)

    private String published

  2. List item

  3. Define the date format

  4. Parse it to date by Java

I think it easier to make your application that can work

CodePudding user response:

java.time

Never use the terrible legacy date-time classes such as Date & Calendar. Use only their successors, the modern java.time classes defined in JSR 310.

Offset-from-UTC

Your input is text in standard ISO 8601 format. That text contains a date, a time-of-day, and a number of hours-minutes-seconds offset from the temporal prime meridian of UTC.

OffsetDateTime

The appropriate class for such an input is OffsetDateTime. That class can directly parse inputs in ISO 8601 format. So no need to define a formatting pattern.

String input = "1901-01-01T00:20:40.000 02:20:40" ;
OffsetDateTime odt = OffsetDateTime.parse( input ) ;

Adjust to an offset of zero.

Instant instant = odt.toInstant() ;

See this code run live at Ideone.com.

odt.toString(): 1901-01-01T00:20:40 02:20:40

instant.toString(): 1900-12-31T22:00:00Z

  • Related