Home > Back-end >  Fetching records that were created 24 hours ago Java
Fetching records that were created 24 hours ago Java

Time:11-08

I have to send records to another system but these records must be sent based on reporting times for different managers.

Say it's Tuesday I have to fetch records that were created from Monday 6 AM till Tuesday 6 AM and send them for reporting that will take place on 7 AM Tuesday. I've been struggling to get the best way to approach this issue maybe you could assist with the best approach to the scenario, below is the solution I came up with:

Date disturbanceDate = disruptionEventEntity.getDisturbanceDate();

Calendar now = Calendar.getInstance();
now.setTime(disturbance data);

Calendar before = Calendar.getInstance();
before.set(Calendar.HOUR_OF_DAY, 6);
before.set(Calendar.MINUTE, 0);
before.set(Calendar.DAY_OF_WEEK,Calendar.MONDAY);
Calendar after = Calendar.getInstance();
after.set(Calendar.HOUR_OF_DAY, 6);
after.set(Calendar.MINUTE, 0);
after.set(Calendar.DAY_OF_WEEK, Calendar.TUESDAY);
boolean between = now.before(after) && now.after(before);
if (between){
  // if the record is in between the two dates send it to the integration system
}

I am not happy with the fact that I have to repeat the same code for other days of the week that's why I would love it if you could suggest a better approach. We are using the date library to record event dates in our system.

CodePudding user response:

var disturbanceDate = disruptionEventEntity.getDisturbanceDate()
  .toInstant()
  .atZone(ZoneId.systemDefault()) // or any other time zone
  .toLocalDateTime();

var todayAtSix = LocalDateTime.of(
  LocalDate.now(ZoneId.systemDefault()),
  LocalTime.of(6,0,0)
);

var yesterdayAtSix = todayAtSix.minusDays(1);
       
if(
  todayAtSix.isAfter(disturbanceDate) &&
  yesterdayAtSix.isBefore(disturbanceDate)
) {
// if the record is in between the two dates send it to the integration system            
}

  • Related