如何在JAVA中计算用户输入的时间

时间:2013-03-01 12:52:08

标签: java date datetime time duration

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

示例:

Startingtime:

小时:15 分钟:50 第二:00

Finishtime:

小时: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 个答案:

答案 0 :(得分: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

答案 1 :(得分:1)

这是ms的差异:

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

您可以将其转换为所需的格式。

答案 2 :(得分: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)

答案 3 :(得分:0)

您可能需要考虑使用JODA时间,它支持更复杂的日期计算方法。