0

显然,Java 中已经有关于计算时间的线程。

但是,我的问题更进一步。我想做的事:

  • 计算开始时间和结束时间之间的差异(已经完成)
  • 将此差异添加回开始时间

一个例子:
Paul 4:00 开始工作,9:00 结束我希望它返回 6:30 (4 + (9-4)/2)

我的代码还:

for (int i = 1, n = licenseplateList.size(); i < n; i++) 
{               
    //first look at whether it is considered as day or night time               
    try {
    String time1 = begintimeList.get(i);
    String time2 = endingtimeList.get(i);

    SimpleDateFormat format = new SimpleDateFormat("HH:mm");
    Date date1 = format.parse(time1);
    Date date2 = format.parse(time2);
    long average = ((date2.getTime() - date1.getTime())/2);

    System.out.println(average);


    }catch (Exception e) {
    }

编辑:
我还想知道我之后如何决定是白天还是晚上(我想使用开始+结束,因为如果超过 18:00,我会考虑在晚上)。但是,我怎样才能在 if 语句中做到这一点?

4

1 回答 1

3

使用(不是那么新的)Java 8 time api,这种计算更容易

public static void main(String[] args) {
    String time1Str = "04:00";
    String time2Str = "09:00";

    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("HH:mm");
    LocalTime time1 = LocalTime.parse(time1Str, formatter);
    LocalTime time2 = LocalTime.parse(time2Str, formatter);
    Duration duration = Duration.between(time1, time2);  // 9-4
    Duration halfDuration = duration.dividedBy(2);  // divided by 2
    LocalTime result = LocalTime.from(halfDuration.addTo(time1));  // added to start time

    System.out.println(result.format(formatter));
}

编辑:在这种情况下支持跨越日期边界的范围
,我们需要将日期值添加到时间。这将告诉 Java 22:00 到 01:00 的范围是“明天”:

public static void main(String[] args) {
    String time1Str = "22:00";
    String time2Str = "01:00";

    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("HH:mm");
    LocalTime time1 = LocalTime.parse(time1Str, formatter);
    LocalTime time2 = LocalTime.parse(time2Str, formatter);

    // add date value: start with today
    LocalDate today = LocalDate.now();
    // combine date time for lower value: will be assigned to today
    LocalDateTime dateTime1 = LocalDateTime.of(today, time1);
    // combine date time for upper value: will be assigned same day if it is after lower value
    // otherwise (we crossed date boundary) assign it to tomorrow
    LocalDateTime dateTime2 =   time2.isAfter(time1) ?
            LocalDateTime.of(today, time2) : LocalDateTime.of(today.plusDays(1), time2);

    Duration duration = Duration.between(dateTime1, dateTime2);
    Duration halfDuration = duration.dividedBy(2);
    LocalTime result = LocalTime.from(halfDuration.addTo(time1));

    System.out.println(result.format(formatter));
}
于 2018-05-17T20:49:42.963 回答