0

我有一个 java 应用程序,其中用户无法在特定日期和时间之后修改订单。例如,用户无法在第 3 天下午 12:00 之前修改订单,例如,如果订单是在 11 月 9 日下达的, 11 月 12 日下午 12:00 之后,用户将无法修改订单。日期是动态的,但时间非常静态。

我试图使用下面的逻辑来计算这个,我无法弄清楚如何从 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>
    }   

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

4

2 回答 2

2

只有当您确定您的程序永远不会在您自己的时区之外使用时,才能安全使用LocalDateTime. 我建议你使用ZonedDateTime以防万一。

无论如何,使用 that 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

于 2019-11-09T19:46:25.297 回答
1

假设您的订单日期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客户可以修改订单之前

if(currentDateTime.isBefore(deadLineDate)) {
    // can modify the order

    }
else {
   //user can not modify the order
}
于 2019-11-09T19:13:01.140 回答