问题出在以下行:
SimpleDateFormat format = new SimpleDateFormat("HH:mm:ss aa");
它应该是:
SimpleDateFormat format = new SimpleDateFormat("hh:mm:ss aa");
该符号H
用于24 小时格式的时间,而h
用于12 小时格式的时间。
你的计算diffMinutes
也是错误的。
执行以下操作:
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
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();
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 = Math.abs(d2.getTime() - d1.getTime());
long diffSeconds = (diff / 1000) % 60;
long diffMinutes = (diff / (60 * 1000));
System.out.print(diffMinutes + " minutes and " + diffSeconds + " seconds.");
} catch (Exception e) {
System.out.println("Invalid fromat");
}
}
}
示例运行:
Enter start time (hh:mm:ss aa): 10:20:30 am
Enter end time (hh:mm:ss aa): 10:20:13 pm
719 minutes and 43 seconds.
笔记:
- 正如@greg-449 所提到的,您应该努力使用现代日期时间 API。
- 两个量之间的差是一个绝对值,始终为正,即 2 和 5 之间的差 = 5 和 2 之间的差 = 3。
Math.abs
为您提供最适合找出两个量之间差的数字的绝对值。
- 您需要了解,在不告知日期的情况下,始终将两次之间的差异视为同一日期,即 12:02:15 am 和 11:58:10 pm 之间的差异 = 11:58:10 pm 和上午 12:02:15 = 1435 分 55 秒。一个日期的 11:58:10 pm 和下一个日期的 12:02:15 am 之间的差异是 4 分 5 秒。但是,您的输入仅用于时间并且没有日期元素,因此已考虑相同日期的差异。下面给出的是考虑时间日期的程序。
考虑带时间的日期的程序:
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter start time (dd.MM.yyyy at hh:mm:ss aa): ");
String starttime = input.nextLine();
System.out.print("Enter end time (dd.MM.yyyy at hh:mm:ss aa): ");
String endtime = input.nextLine();
SimpleDateFormat format = new SimpleDateFormat("dd.MM.yyyy 'at' hh:mm:ss aa");
Date d1 = null;
Date d2 = null;
try {
d1 = format.parse(starttime);
d2 = format.parse(endtime);
// in milliseconds
long diff = Math.abs(d2.getTime() - d1.getTime());
long diffSeconds = (diff / 1000) % 60;
long diffMinutes = (diff / (60 * 1000));
System.out.print(diffMinutes + " minutes and " + diffSeconds + " seconds.");
} catch (Exception e) {
System.out.println("Invalid fromat");
}
}
}
示例运行:
Enter start time (dd.MM.yyyy at hh:mm:ss aa): 03.03.2020 at 11:58:10 pm
Enter end time (dd.MM.yyyy at hh:mm:ss aa): 04.03.2020 at 12:02:15 am
4 minutes and 5 seconds.