Home > Software engineering >  Java Instance Calculate Duration between the Instant
Java Instance Calculate Duration between the Instant

Time:04-16

public class Student {
    String firstName;
    String secondName;
    Instant lastClassAttendedOn;
}

Hi, I have been stuck on a problem where I have the list of students and I want to find out all the students who have attended at least one class in the previous week. By previous week, I mean from the previous week Monday to the previous week Friday as the school has a holiday on Saturday and Sunday. I might be checking the list any day of the week for example On Wednesday so I should get all the students who have taken at least a class in previous week

CodePudding user response:

As we are dealing with only days, it's sufficient to use LocalDate. Find out the start and end dates of the previous week from the current/ today's date. Then loop through the list and filter out the results from the start date.

LocalDate currentDate = LocalDate.now();

LocalDate start = currentDate.with(TemporalAdjusters.previous(DayOfWeek.MONDAY));
LocalDate end = currentDate.with(TemporalAdjusters.previous(DayOfWeek.FRIDAY));
for(Student student : studentsList) {
    Instant lastAccessedOn = student.getLastAccessedOn();
    LocalDate accessedDate = 
        lastAccessedOn.atZone(ZoneId.systemDefault()).toLocalDate();

    int noOfDays = start.until(accessedDate).getDays();
    if (noOfDays >= 0 && noOfDays <= 4) {
        // match found. Take this student
    }
}

Here, noOfDays may have negative values if the accessedDate lies in older weeks. So, check for >= 0. And we want to restrict till previous week's Friday. So it should be <= 4.

  • Related