-1

嘿伙计们,我需要帮助来弄清楚如何计算两个特定时间之间的时间差(由用户输入)。但是输出必须以小时、分钟和秒为单位作为它们自己的变量进行拆分。

例子:

起始时间:

小时:15 分钟:50 秒:00

结束时间:

小时:17 分钟:14 秒:23

结果:1小时24分23秒

编辑:这是我到目前为止所得到的,这是我的问题的计算

public static void main(String[] args) 
{
    Scanner in = new Scanner(System.in);
    System.out.println("Starttime:");
    System.out.println("---------");

    System.out.print("Hour: ");
    int HourS = in.nextInt();
    System.out.print("Minute: ");
    int minuteS = in.nextInt();
    System.out.print("Second: ");
    int secondS = in.nextInt();


    System.out.println("\t");

    System.out.println("Finishtime:");
    System.out.println("------------");

    System.out.print("Hour: ");
    int hourF = in.nextInt();
    System.out.print("Minute: ");
    int minuteF = in.nextInt();
    System.out.print("Second: ");
    int secondM = in.nextInt();
4

4 回答 4

2

使用 JodaTime - 它做得很好。

这个简单的示例计算两个时间戳之间的差异并打印出人类可读的:

    String a = "00:01:09:340";
    String b = "00:02:03:430";

    DateTimeFormatter format = DateTimeFormat.forPattern("HH:mm:ss:SSS");
    DateTime oldTime = DateTime.parse(a, format);
    DateTime newTime = DateTime.parse(b, format);
    Interval interval = new Interval(oldTime, newTime);

    System.out.println(new StringBuffer("hours: ").append(interval.toDuration().getStandardHours())
            .append(" minutes: ").append(interval.toDuration().getStandardMinutes()).append(" seconds: ")
            .append(interval.toDuration().getStandardSeconds()).append(" milliseconds: ")
            .append(interval.toPeriod().getMillis()).toString());

该示例将为您提供以下输出:

hours: 0 minutes: 0 seconds: 54 milliseconds: 90
于 2013-03-01T13:00:34.090 回答
1
public static void main (String [] args) throws Exception
{
    SimpleDateFormat format = new SimpleDateFormat ("'Hour: 'HH' Minute: 'mm' Second: 'ss");

    BufferedReader reader = 
        new BufferedReader (
            new InputStreamReader (System.in));

    System.out.print ("Starting time: ");
    long startingTime = format.parse (reader.readLine ()).getTime ();
    System.out.print ("Finish time: ");
    long finishTime = format.parse (reader.readLine ()).getTime ();

    long delta = finishTime - startingTime;

    long seconds = delta / 1000 % 60;
    long minutes = delta / 60000 % 60;
    long hours = delta / 3600000;

    System.out.println (
        "Result: " + hours + " hour(s) " + minutes + 
        " minute(s) " + seconds + " second(s)");
}

对我来说输出是:

Starting time: Hour: 15 Minute: 50 Second: 00
Finish time: Hour: 17 Minute: 14 Second: 23
Result: 1 hour(s) 24 minute(s) 23 second(s)
于 2013-03-01T12:59:45.903 回答
1

这是以毫秒为单位的差异:

SimpleDateFormat format = new SimpleDateFormat("HH:mm:ss");
Date date = format.parse(time);
Date dateB = format.parse(timeB);
long difference = dateB.getTime() - date.getTime();

您可以将其转换为您想要的格式。

于 2013-03-01T12:55:15.830 回答
0

您可能想考虑使用 JODA-time,它支持更复杂的日期计算方法。

于 2013-03-01T12:56:06.360 回答