Reputation: 269
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;
}
Upvotes: 1
Views: 2440
Reputation: 512
Take the difference and and call the method; long diff = dt2.getTime() - dt1.getTime();
public static String toHumanReadableTime(long diff) {
Long hour = TimeUnit.HOURS.convert(diff, TimeUnit.MILLISECONDS);
diff= diff% (1000 * 60 * 60);
Long minutes = TimeUnit.MINUTES.convert(diff, TimeUnit.MILLISECONDS);
diff= diff% (1000 * 60);
Long seconds = TimeUnit.SECONDS.convert(diff, TimeUnit.MILLISECONDS);
diff= diff% 1000;
Long milisec = diff;
StringBuilder buffer = new StringBuilder();
if (hour != null && hour > 0) {
buffer.append(hour).append(" Hour ");
}
if (minutes != null && minutes > 0) {
buffer.append(minutes).append(" Minute ");
}
buffer.append(seconds).append(" Second ");
buffer.append(milisec).append(" Millisecond ");
return buffer.toString();
}
Upvotes: 0
Reputation: 3119
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;
}
Since your Dates aren't in their default format you will have to use a SimpleDateFormat to explicitly declare the format of your Dates.
Upvotes: 2
Reputation: 1354
Try Using This
try {
/// String CurrentDate= "10/6/2016";
/// String PrviousDate= "10/7/2015";
Date date1 = null;
Date date2 = null;
SimpleDateFormat df = new SimpleDateFormat("MM/dd/yyyy");
date1 = df.parse(CurrentDate);
date2 = df.parse(PrviousDate);
long diff = Math.abs(date1.getTime() - date2.getTime());
long diffDays = diff / (24 * 60 * 60 * 1000);
System.out.println(diffDays);
} catch (Exception e) {
System.out.println("exception " + e);
}
Upvotes: 0
Reputation: 21
From here
long diff = dt2.getTime() - dt1.getTime();
long diffSeconds = diff / 1000 % 60;
long diffMinutes = diff / (60 * 1000) % 60;
long diffHours = diff / (60 * 60 * 1000);
int diffInDays = (int) ((dt2.getTime() - dt1.getTime()) / (1000 * 60 * 60 * 24));
Upvotes: 0