spring json 解析日期包含小时数

spring json parsed Date contains hours

我有一个 spring 应用程序使用了这样的实体:

@Getter
@Setter
class Entity {
    private Date delay;
}

我将以下 json 传递给 spring 端点。

{
  "delay": "2022-05-15"
}

当我调用 entity.getDelay().getTime() 时,我得到 1652572800 这是过去的日期加上 2 小时。

我想要接收 0 小时的日期,因为我需要将该值与存储在没有小时和分钟的数据库中的值进行比较。

你知道怎么做吗?

Java 8 brought a lot of language improvements. One of those is the new Date and Time API for Java. The new Date and Time API is moved to java.time package. The new java.time package contains all the classes for date, time, date/time, time zones, instants, duration, and clocks manipulation.

示例类:

  • 时钟
  • 本地日期
  • 地区时间
  • 本地日期时间
  • 持续时间

使用 LocalDate 的示例

public class YourDto {

    private LocalDate delay;
........//todo
}

像下面这样找到你的日、年、月

   //Using LocalDate

    // Month value
    (dto.getDelay().getMonth().getValue()); == 5

    // Month
    (dto.getDelay().getMonth()); == May

    // Day
    (dto.getDelay().getDayOfMonth()); == 15

    // Year
    (dto.getDelay().getYear()); == 2022

    // Date
    (dto.getDelay()); == 2022-05-15

将 LocalDate 转换为毫秒,反之亦然

       // Convert LocalDate to Milliseconds
        long time = dto.getDelay().atStartOfDay(ZoneOffset.UTC).toInstant().toEpochMilli();
        System.out.println("Time in millisecoinds = " + time);
        // Convert Milliseconds to LocalDate
        LocalDate myDate = LocalDate.ofEpochDay(Duration.ofMillis(time).toDays());
        System.out.println("LocalDate = " + myDate);    

根据@Ole V.V.的建议。

// Convert Milliseconds to LocalDate
    LocalDate myDate = Instant.ofEpochMilli(time).atOffset(ZoneOffset.UTC).toLocalDate();

UTC is not a time zone, but a time standard that is the basis for civil time and time zones worldwide.

Ref