-1

我有两个日期值。

  1. Date now=new Date();
  2. 另一个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();  

像这样的东西

4

3 回答 3

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
于 2013-07-11T08:24:35.820 回答
0

java.util.date

int diffInDays = (int)((newDate.getTime() - oldDate.getTime()) / (1000*60*60*24))

请注意,这适用于 UTC 日期。

于 2013-07-11T08:22:57.260 回答
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
于 2013-07-11T09:35:27.967 回答