gpt4 book ai didi

java - Java AM/PM 时差

转载 作者:行者123 更新时间:2023-12-01 19:28:39 25 4
gpt4 key购买 nike

我试图通过输入时间格式计算12小时内的java时差,当我输入开始时间11:58:10 pm和结束时间12:02时效果很好:15 点。但当我输入 12:00:00 am 和 12:00:00 pm 时,它会给出 0 分钟的差异。不知道为什么。下面是我的代码,请告诉我哪里错了。

Scanner input = new Scanner(System.in);
System.out.print("Enter start time (HH:mm:ss aa): ");
String starttime = input.nextLine();

System.out.print("Enter end time (HH:mm:ss aa): ");
String endtime = input.nextLine();

//HH converts hour in 24 hours format (0-23), day calculation
SimpleDateFormat format = new SimpleDateFormat("HH:mm:ss aa");

Date d1 = null;
Date d2 = null;

try {
d1 = format.parse(starttime);
d2 = format.parse(endtime);

//in milliseconds
long diff = d2.getTime() - d1.getTime();

long diffSeconds = diff / 1000 % 60;
long diffMinutes = diff / (60 * 1000) % 60;

System.out.print(diffMinutes + " minutes and "+diffSeconds + " seconds.");
} catch (Exception e) {
System.out.println("Invalid fromat");
}

最佳答案

新的java.time方法LocalTimeDateTimeFormatterDuration提供了更好的方法来处理这个问题。例如:

DateTimeFormatter format = DateTimeFormatter.ofPattern("h:m:s a");

LocalTime time1 = LocalTime.parse("12:00:00 am", format);
LocalTime time2 = LocalTime.parse("2:00:20 pm", format);

Duration dur = Duration.between(time1, time2);

System.out.println(dur.toMinutes() + " minutes " + dur.toSecondsPart() + " seconds");

注意:Duration.toSecondsPart 需要 Java 9 或更高版本,此代码的其余部分需要 Java 8 或更高版本。

关于java - Java AM/PM 时差,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60512711/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com