-1

I have two date values.

  1. Date now=new Date();
  2. Another date variable.

I want to find out the difference bet them in xxxDays XXXHours XXMin XXXSeconds.How can I achieve this.

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();  

Some thing like this

ozahorulia
  • 9,798
  • 8
  • 48
  • 72
user1281029
  • 1,513
  • 8
  • 22
  • 32

3 Answers3

1

The difference you get from two dates is in miliseconds, so your code should look something like this:

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
Gintas K
  • 1,438
  • 3
  • 18
  • 38
0

With java.util.date:

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

Note that this works with UTC dates.

perror
  • 7,071
  • 16
  • 58
  • 85
Fonexn
  • 189
  • 4
  • 15
0

Another approach using 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);   

Which correctly prints:

2 days, 2 hours, 2 mins
Adam Siemion
  • 15,569
  • 7
  • 58
  • 92