我有两个日期值。
Date now=new Date();
date
变量。我想找出他们在xxxDays XXXHours XXMin XXXSeconds中的差异。我怎样才能实现这一目标。
Date now=new Date();
Date date2="2013-07-04 18:06:27"; //(I will get this from a DB).
String/Date dateDiff=date2.getTime()-now.getTime();
有点像这样
答案 0 :(得分:1)
从两个日期获得的差异以毫秒为单位,因此您的代码应如下所示:
var difference = date1 - date2;
var days = difference / (1000*60*60*24);
var hours = (difference - days*1000*60*60*24) / (1000*60*60);
var minutes = (difference - days*1000*60*60*24 - hours*1000*60*60) / (1000*60)
var seconds = (difference - days*1000*60*60*24 - hours*1000*60*60 - minutes*1000*60)/ 1000
答案 1 :(得分:0)
使用java.util.date
:
int diffInDays = (int)((newDate.getTime() - oldDate.getTime()) / (1000*60*60*24))
请注意,这适用于UTC日期。
答案 2 :(得分:0)
使用TimeUnit
final SimpleDateFormat fmt = new SimpleDateFormat("dd/MM/yyyy HH:mm");
final Date old = fmt.parse("10/7/2013 10:10");
final Date now = fmt.parse("12/7/2013 12:12");
long dif = now.getTime() - old.getTime();
final long days = TimeUnit.MILLISECONDS.toDays(dif);
dif -= TimeUnit.DAYS.toMillis(days);
final long hours = TimeUnit.MILLISECONDS.toHours(dif);
dif -= TimeUnit.HOURS.toMillis(hours);
long mins = TimeUnit.MILLISECONDS.toMinutes(dif);
System.out.format("%d days, %d hours, %d mins\n", days, hours, mins);
哪个正确打印:
2 days, 2 hours, 2 mins