如何找到两个日期之间的差异持续时间 [英] How to find the duration of difference between two dates
本文介绍了如何找到两个日期之间的差异持续时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有两个约会,例如。 1989-3-21、2016-3-21,我想找出两个日期之间的差值持续时间。为此,我正在尝试以下代码,但无法获得日期差的持续时间。
I have two dates, eg. 1989-3-21, 2016-3-21 and I want to find the duration of difference between those dates. For this I am trying the following code but I am unable to get the duration of difference in dates.
public String getTimeDiff(Date dateOne, Date dateTwo) {
String diff = "";
long timeDiff = Math.abs(dateOne.getTime() - dateTwo.getTime());
diff = String.format("%d hour(s) %d min(s)", TimeUnit.MILLISECONDS.toHours(timeDiff),
TimeUnit.MILLISECONDS.toMinutes(timeDiff) - TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(timeDiff)));
return diff;
}
推荐答案
像以前一样初始化日期调用公用字符串getTimeDiff(Date dateOne,Date dateTwo)
:
Initialize your dates like so before calling public String getTimeDiff(Date dateOne, Date dateTwo)
:
Date dateOne=null,dateTwo=null;
try {
dateOne = new SimpleDateFormat( "yyyy-MM-dd" ).parse("2016-3-21");
dateTwo = new SimpleDateFormat( "yyyy-MM-dd" ).parse("1989-3-21");
}
catch (ParseException ex) {
}
System.out.println( getTimeDiff(dateOne,dateTwo));
public String getTimeDiff(Date dateOne, Date dateTwo) {
String diff = "";
long timeDiff = Math.abs(dateOne.getTime() - dateTwo.getTime());
diff = String.format("%d date(s) ", TimeUnit.MILLISECONDS.toDays(timeDiff));
return diff;
}
由于您的日期不是默认格式,因此您必须使用SimpleDateFormat显式声明日期的格式。
Since your Dates aren't in their default format you will have to use a SimpleDateFormat to explicitly declare the format of your Dates.
这篇关于如何找到两个日期之间的差异持续时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文