简体   繁体   中英

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

I have a java application where in the User can not modify the order after a specific date and time.eg.the user can not modify the order after the 3rd day by 12:00 PM,say if the order was placed on Nov 9th,the user will not be able to modify the oder after Nov 12th,12:00 PM.The Date is Dynamic but the time is very much static.

I was trying to use the below logic to calculate this and i am unable to figure out how to extract the current time from LocalDateTime.now() for comparison.

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>
    }   

Can anyone help me with an efficient way to do this comparison.

Only if you know for sure that your program will never be used outside your own time zone, is it safe to use LocalDateTime . I receommend you use ZonedDateTime just in case.

In any case, using that LocalDateTime , the code for your logic as I have understood it is:

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,");
}

Of course substitute your own time zone where I put America/Punta_Arenas .

Suppose if you have the oder date in LocalDate as today

LocalDate orderDate //2019-11-09

Now create the deadline date by adding 3 days to it

LocalDateTime deadLineDate =orderDate.plusDays(3).atStartOfDay(); //2019-11-12T00:00

Even if you want a particular time you can use atTime methods

LocalDateTime deadLineDate =orderDate.plusDays(3).atTime(12,0);

So if currentDateTime is before the deadLineDate customer can modify the order

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM