从使用 to_date 的数据库测试日期并针对 LocalTimeDate 进行测试

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

我有一个旧程序,我将它升级到 Java 8. 现在我想利用 LocalDateTime。我已经更新了实体,并且在数据库中的值显示为 10-APR-1990.

但是我收到以下错误:

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

在我的测试中,我尝试使用 DateTimeFormatter 来解析它。

测试:

@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());
    }

两件事:

  • 月份需要采用驼峰式:"10-Apr-90".
  • 因为您正在解析的内容没有时间方面,所以您应该使用 LocalDate 而不是 LocalDateTime

更新您的测试用例以使用不区分大小写的格式化程序并将日期字符串解析为 LocalDate,并将时间设置为一天的开始以获取 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());

}