【问题标题】:Time difference in AM/PM in JavaJava 中 AM/PM 的时差
【发布时间】:2020-03-03 17:34:11
【问题描述】:

我试图通过输入时间格式在 12 小时内计算 java 中的时差,当我输入开始时间11:58:10 pm 和结束时间12:02:15 am 时效果很好。但是当我进入上午 12:00:00 和下午 12:00:00 时,它会产生 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");
}

【问题讨论】:

  • HH 预计小时为 24 格式,而不是 12。
  • HH 是 24 小时制,请改用 hh。最好不要使用像 DateSimpleDateFormat 这样的旧类。一方面,它们并非旨在代表挂钟时间。使用LocalTimeDateTimeFormatter
  • 我使用了 hh 格式但还是一样
  • 必须是DateSimpleDateFormat 吗?这些被认为是过时的,新代码应该使用LocalTimeDateTimeFormatterDuration进行计算。
  • 请使用java.time

标签: java time duration timeofday


【解决方案1】:

新的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 或更高版本。

【讨论】:

  • 该类未被弃用,虽然我不不同意这更好,但有时您必须使用Date
  • @Makoto 喜欢当你有一个邪恶的老板这么说的时候?我能想到的情况非常非常少。
  • @OleV.V.:据我了解,Hibernate 存在一些问题;可能没有动力从Date 更改为LocalDateLocalDateTime,因为这可能会破坏正在维护的代码中的合同;等等。它并不总是必须是某人或某事的混合体。
  • 坦率地说,@Makoto,你在说什么?问题是关于有两个字符串并计算它们之间的分钟和秒,据我们所知,不涉及持久性。 (除此之外,我的 Hibernate 5 一直与 java.time 完美配合。)
  • 公平...我认为我的头在不同的空间@OleV.V.。但是,我看不出仅仅因为错字而使用不同的类的价值(正如我们建立的, 应该是小写 hh 而不是大写)。同样,有时您只是必须使用它。
【解决方案2】:

问题出在以下行:

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.

注意事项:

  1. 正如@greg-449 所说,您应该努力使用modern date-time API
  2. 两个量之间的差是一个绝对值,始终为正,即 2 和 5 之间的差 = 5 和 2 之间的差 = 3。Math.abs 为您提供最适合找出差的数字的绝对值在两个数量之间。
  3. 您需要了解,在不告知日期的情况下,始终将两次之间的差异视为同一日期,即 12:02:15 am 和 11:58:10 pm 之间的差异 = 11:58 之间的差异:晚上 10 点和上午 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.

【讨论】:

  • 它在 11:58:10 pm 和 12:02:15 am 的时间不准确
  • 我已经用一些注释更新了答案。我希望,它会有所帮助。
猜你喜欢
  • 2012-02-18
  • 2022-01-19
  • 1970-01-01
  • 2014-02-06
  • 2021-11-15
  • 1970-01-01
  • 2021-02-24
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多