使用Java-8 LocaldateTime比较日期和时间(提前三天)

我有一个Java应用程序,在该应用程序中,用户无法在特定的日期和时间后修改订单。例如,用户不能在第三天下午12:00之后修改订单,例如是否下达订单11月9日,用户将无法在11月12日中午12:00之后修改oder。日期是动态的,但时间是非常固定的。

我试图使用以下逻辑来计算该时间,但是我无法弄清楚如何从LocalDateTime.now()中提取当前时间进行比较。

final LocalDate orderDate  =orderData.getOrderDate.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
final LocalDate currentDate = LocalDate.now();
final LocalDateTime currentDateTime = LocalDateTime.now();
final LocalDate orderCancellationCutOffDate = 
orderDate.minusDays(orderCancellationCutOffDays);

if (currentDate.equals(orderCancellationCutOffDays) && 
currentDateTime.isBefore(<12:00 PM>)){

<Business rule>
    }   

任何人都可以通过一种有效的方式帮助我进行比较。

chimeralinux 回答:使用Java-8 LocaldateTime比较日期和时间(提前三天)

仅当您确定无法在自己的时区之外使用程序时,才可以安全使用LocalDateTime。我建议您使用ZonedDateTime以防万一。

无论如何,使用该LocalDateTime,据我所知,您的逻辑代码为:

final int orderCancellationCutOffDays = 3;
final LocalTime orderCancellationCutOffTime = LocalTime.of(12,0);

LocalDate orderDate = LocalDate.of(2019,Month.NOVEMBER,6);
LocalDateTime orderCancellationCutOffDateTime
        = orderDate.plusDays(orderCancellationCutOffDays)
                .atTime(orderCancellationCutOffTime);
final LocalDateTime currentDateTime = LocalDateTime.now(ZoneId.of("America/Punta_Arenas"));
if (currentDateTime.isAfter(orderCancellationCutOffDateTime)) {
    System.out.println("This order can no longer be modified.");
} else {
    System.out.println("You can still modify this order,");
}

当然可以用您自己放置America/Punta_Arenas的时区代替。

,

假设您在const {error} = this.state; 中的截止日期是今天

LocalDate

现在通过向其添加LocalDate orderDate //2019-11-09 天来创建截止日期

3

即使您想要特定的时间,也可以使用LocalDateTime deadLineDate =orderDate.plusDays(3).atStartOfDay(); //2019-11-12T00:00 方法

atTime

因此,如果LocalDateTime deadLineDate =orderDate.plusDays(3).atTime(12,0); currentDateTime客户之前可以修改订单

deadLineDate
本文链接:https://www.f2er.com/3131654.html

大家都在问