I want the program to check if current time hits midnight, 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 is in, might not get called when midnight occurs exactly. Is there a way of checking if next day occurs or similar?
I'm trying to do a daily file rollover for binary files (and log4j doesn't do binary) using an if statement.
Since you don't know when your method will be called, I suggest you to save the date for comparison and forget the clock time part or if midnight has been hit.
private LocalDate lastCheck = null;
public boolean isNewDay() {
LocalDate today = LocalDate.now();
boolean ret = lastCheck == null || today.isAfter(lastCheck);
lastCheck = today;
return ret;
}
Well, for the question if midnight has been hit during your method call you can use 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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With