-1

可能的重复:
计算两个 Java 日期实例之间的差异

我在 HH:MM:SS 格式的字符串数据类型的两个文本框中有两个日期值。我怎样才能找到它们之间的差异并得到 HH:MM:SS 的结果?请帮助我......尽快...... !

4

3 回答 3

3

尝试这个:

     SimpleDateFormat format = new SimpleDateFormat("hh:mm:ss");
     format.setTimeZone(TimeZone.getTimeZone("UTC"));
     try {
         Date date1 = (Date) format.parse("4:15:20");
         Date date2 = (Date) format.parse("2:30:30");
         //time difference in milliseconds
         long timeDiff = date1.getTime() - date2.getTime(); 
         //new date object with time difference
         Date diffDate = new Date(timeDiff); 
         //formatted date string
         String timeDiffString = format.format(diffDate); 
         System.out.println("Time Diff = "+ timeDiffString );
     } catch (ParseException e) {
         // TODO Auto-generated catch block
         e.printStackTrace();
     }

以上代码有一定的局限性。其他正确的方法可能是在字符串中手动转换长时差值,如下所示:

     long timeDiffSecs = timeDiff/1000;
     String timeDiffString = timeDiffSecs/3600+":"+
                             (timeDiffSecs%3600)/60+":"+
                             (timeDiffSecs%3600)%60;
     System.out.println("Time Diff = "+ timeDiffString);
于 2012-12-25T04:56:22.970 回答
0

您拥有的代码将为您提供所列日期之间的毫秒数差异。答案可能是简单地除以 1000 以获得秒数。

于 2012-12-25T04:37:20.037 回答
0

首先将字符串日期转换为简单的日期格式

public String getconvertdate1(String date)
{
    DateFormat inputFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    inputFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
    DateFormat outputFormat = new SimpleDateFormat("dd MMM yyyy");
    Date parsed = new Date();
    try
    {
        parsed = inputFormat.parse(date);
    }
    catch (ParseException e)
    {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    String outputText = outputFormat.format(parsed);
    return outputText;
}

//现在可以对日期做任何事情。

 long diff = today.getTimeInMillis() - thatDay.getTimeInMillis(); //result in millis
 long days = diff / (24 * 60 * 60 * 1000);// you get day difference between

并使用 simpledateFormate 配置 HH:MM:SS

于 2012-12-25T06:11:27.210 回答