简体   繁体   English

如何在 Java 中返回 LocalTime 的总和

[英]How to return sum of LocalTime in Java

It wont get the minutes.它不会得到分钟。 i need to return minutes.我需要返回分钟。 How to return sum of minutes while iterating over Localtime in Java?如何在 Java 中迭代 Localtime 时返回分钟总和?

public String userLunchHoursSum(String username) {
    List<WorkHour> workHours = workHourRepository.findWorkHoursByUsername(username);
    System.out.println(Arrays.toString(workHours.toArray()));
    long diff = 0;
    LocalTime lunchTime;
    long minutes = 0;
    LocalTime plusMinutes = null;
    for (WorkHour workHour : workHours) {
        lunchTime = workHour.getLunch_time().toLocalTime(); //00:30:00
        plusMinutes = lunchTime.plusMinutes(lunchTime.getMinute());
    }
    if(workHours.size()!= 0) {
        return Long.toString(plusMinutes.getMinute());
    }
    return "00:00";
}

getLunch_time returns java.sql.Time . getLunch_time返回java.sql.Time

As mentioned, you should be storing duration instead of localtime.如前所述,您应该存储持续时间而不是本地时间。 If this is something you have no control over, consider migrating the database or creating a intermediate parsing function.如果这是您无法控制的,请考虑迁移数据库或创建中间解析 function。 Example code that I have not run, because I don't know what is in WorkHour .我没有运行的示例代码,因为我不知道WorkHour中有什么。

// leave the string formatting to other functions
public long userLunchHoursSum(String username) {
    List<WorkHour> workHours = workHourRepository.findWorkHoursByUsername(username);
    Duration totalDuration = Duration.ZERO;
    for (WorkHour workHour : workHours) {
        // save your time in the appropriate format beforehand
        // do not use local time to store duration.
        Duration lunchTime = Duration.between(LocalTime.MIDNIGHT, workHour.getLunch_time().toLocalTime()); //00:30:00
        totalDuration = totalDuration.plus(lunchTime);
    }
    return totalDuration.toMinutes();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM