Logo Questions Linux Laravel Mysql Ubuntu Git Menu

Check if the current time hits midnight/or is next day in Joda Time?




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.

like image 527
Adz Avatar asked Mar 18 '23 08:03


1 Answers

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
like image 173
Meno Hochschild Avatar answered Mar 26 '23 04:03

Meno Hochschild