Java实例计算即时之间的持续时间

发布于 2025-01-20 13:19:13 字数 253 浏览 0 评论 0原文

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

嗨,我一直遇到一个学生名单的问题,我想找出上周至少参加过一堂课的所有学生。到上周,我的意思是从上一周的星期一到上一周星期五,因为学校在星期六和周日有一个假期。例如,我可能会在星期三的任何一天检查列表,所以我应该让所有上一周至少上课的学生

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

因为看清所以看轻 2025-01-27 13:19:13

由于我们仅处理几天,因此使用localdate就足够了。从当前/今天的日期开始找出上周的起点和结束日期。然后循环浏览列表,并从开始日期开始滤除结果。

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
    }
}

在这里,noofays如果accesseddate在较早的几周内,则可能具有负值。因此,请检查&gt; = 0。我们要限制到上周的星期五。因此应该为&lt; = 4。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文