以时间格式 hh:mm:ss java 计算两个小时之间的时差

Ema*_*fer 1 java datetime date

我正在尝试计算两个小时之间的差异。时间格式必须是 hh:mm:ss!我实现了这个代码:

public static String timeDifference(long timeDifference1) {

    long timeDifference = timeDifference1 / 1000;
    int h = (int) (timeDifference / (3600));
    int m = (int) ((timeDifference - (h * 3600)) / 60);
    int s = (int) (timeDifference - (h * 3600) - m * 60);

    return String.format("%02d:%02d:%02d", h, m, s);
}

public static void main(String[] args) throws ParseException {
    Scanner sc = new Scanner(System.in);
    while (sc.hasNext()) {
        String timeStart = sc.next();
        String timeStop = sc.next();
        char lol[]=timeStop.toCharArray();
        if(lol[0]=='0' && lol[1]=='0'){
            lol[0]='2';
            lol[1]='4';
        }
        String tetx=String.valueOf(lol);
        timeStop=tetx;

        char kk[]=timeStart.toCharArray();
        if(kk[0]=='0' && kk[1]=='0'){
            kk[0]='2';
            kk[1]='4';
        }
        String hhh=String.valueOf(kk);
        timeStart=hhh;

        SimpleDateFormat format = new SimpleDateFormat("hh:mm:ss");

        Date d1 = null;
        Date d2 = null;

        d1 = format.parse(timeStart);
        d2 = format.parse(timeStop);

        long diff;

        if (d1.getTime() > d2.getTime()) {
            diff = (int) (d1.getTime() - d2.getTime());

        } else
            diff = (int) (d2.getTime() - d1.getTime());

        System.out.println(timeDifference(diff));

    }
}
Run Code Online (Sandbox Code Playgroud)

输入必须是:

10:03:43 15:00:58

13:00:00 14:00:00

00:00:00 12:05:00

12:05:00 00:00:00
Run Code Online (Sandbox Code Playgroud)

和输出:

04:57:15

01:00:00

12:05:00

11:55:00 
Run Code Online (Sandbox Code Playgroud)

但我明白了

04:57:15

01:00:00

00:05:00

00:05:00 
Run Code Online (Sandbox Code Playgroud)

我怎样才能解决这个问题?

Mic*_*ael 5

不要重新发明轮子。您可以使用该java.time软件包完成所有这些操作。

一旦我们要求第二个值00:00:00代表明天,逻辑就会变得不那么优雅。我们需要使用LocalDateTimes 并可能增加一天:

private static String getDifference(final String first, final String second)
{
    final LocalTime firstTime = LocalTime.parse(first, DateTimeFormatter.ISO_LOCAL_TIME);
    final LocalTime secondTime = LocalTime.parse(second, DateTimeFormatter.ISO_LOCAL_TIME);

    final LocalDateTime firstDateTime = LocalDateTime.of(LocalDate.now(), firstTime);
    final LocalDateTime secondDateTime = LocalDateTime.of(
        LocalDate.now().plusDays(second.equals("00:00:00") ? 1 : 0),
        secondTime
    );

    final Duration diff = Duration.between(firstDateTime, secondDateTime).abs();

    return String.format(
        "%02d:%02d:%02d",
        diff.toDaysPart() < 1 ? diff.toHoursPart() : 24,
        diff.toMinutesPart(),
        diff.toSecondsPart()
    );
}
Run Code Online (Sandbox Code Playgroud)

像这样调用:

System.out.println(getDifference("12:05:00", "00:00:00"));
Run Code Online (Sandbox Code Playgroud)

示例输出:

11:55:00


请注意toMinutesPartJDK 9 中添加了它和它的兄弟方法。 JDK 8 中的逻辑非常相似,但更加冗长。