Search code examples
javaunit-testingjava-8localdate

Testing a Date from a database that uses to_date and testing against LocalTimeDate


I have a old program and I upgraded it to Java 8. Now I would like to take advantage of LocalDateTime. I have already updated the entity and in the Database the value reads 10-APR-1990.

However I am getting the following error:

java.time.format.DateTimeParseException: Text '10-APR-90' could not be parsed at index 3

In my test I attempt to parse it using DateTimeFormatter.

Test:

@Test
    public void testLocalDateTime() throws Exception {

        DateTimeFormatter formatter =
                DateTimeFormatter.ofPattern("dd-MMM-yy", Locale.US);

        Tcan1990 applicant = tcan1990Repository.findOne(new Tcan1990PK("000000009", 888067));

        assertEquals(LocalDateTime.parse("10-APR-90",formatter),applicant.getPymtDt());
    }

Solution

  • Update your test case to use case insensitive formatter and parse the date string to LocalDate with time set to start of the day to get the LocalDateTime.

    @Test
    public void testLocalDateTime() throws Exception {
    
        DateTimeFormatter formatter = new DateTimeFormatterBuilder().parseCaseInsensitive().appendPattern("dd-MMM-yyyy").toFormatter(Locale.US);
    
        Tcan1990 applicant = tcan1990Repository.findOne(new Tcan1990PK("000000009", 888067));
    
        assertEquals(LocalDate.parse("10-APR-1990", formatter).atStartOfDay(), applicant.getPymtDt());
    
    }