Make sure the current time reaches midnight / or the next day at Joda Time?
I want the program to check if the current time reaches midnight and then do something.
I've tried this:
if (DateTime.now() == DateTime.now().withTimeAtStartOfDay()) {
//do stuff
}
The problem is that most of the time, the method that this function resides in may not be called when the completeness happens exactly. Is there a way to check if the next day or something similar happens?
I am trying to do a daily file poll for binaries (and log4j does not execute binary) using an if statement.
+3
source to share
1 answer
Since you donβt know when your method will be called, I suggest you keep the date for comparison and forget the clock time part or if midnight was attacked.
private LocalDate lastCheck = null;
public boolean isNewDay() {
LocalDate today = LocalDate.now();
boolean ret = lastCheck == null || today.isAfter(lastCheck);
lastCheck = today;
return ret;
}
It's good that if it was received during the method call, you can use the following scheme:
DateTime now = DateTime.now();
DateTime startOfDay = now.withTimeAtStartOfDay();
DateTime latest = startOfDay.plusMinutes(1); // tolerance, you can adjust it for your needs
if (new Interval(startOfDay, latest).contains(now)) {
// do stuff
}
+4
source to share