Reputation: 353
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.
Upvotes: 0
Views: 1026
Reputation: 86323
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
.
Upvotes: 2
Reputation: 40078
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
}
Upvotes: 2