簡體   English   中英

使用 Java-8 LocaldateTime 將日期和時間與提前三天進行比較

[英]Comparing Date and Time with three days ahead using Java-8 LocaldateTime

我有一個 java 應用程序,其中用戶無法在特定日期和時間之后修改訂單。例如,用戶無法在第 3 天下午 12:00 之前修改訂單,例如,如果訂單是在 11 月 9 日下達的, 11 月 12 日下午 12:00 后用戶將無法修改訂單。日期是動態的,但時間非常多 static。

我試圖使用下面的邏輯來計算這個,我無法弄清楚如何從 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>
    }   

任何人都可以幫助我以一種有效的方式進行這種比較。

只有當您確定您的程序永遠不會在您自己的時區之外使用時,使用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的時區替換您自己的時區。

假設您在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);

所以如果currentDateTimedeadLineDate之前客戶可以修改訂單

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

    }
else {
   //user can not modify the order
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM