Reputation: 641
I have android application and I need to display the different between two date but I have a problem in this case
For example : When tried to display the different between date 28/12/2016 and 01/01/2017
the result is 339 days , How I can solve this and when tried to display, I got a correct result. This is my code:
public void Cal() {
java.text.SimpleDateFormat simpleDateFormat =new java.text.SimpleDateFormat("yyyy/mm/dd hh:mm:ss");
try {
Date date2 = simpleDateFormat.parse("2017/01/01"+ " " + "11:30:00");//end_date
Date date1 = simpleDateFormat.parse("2016/12/28"+ " " + "11:30:00");//start_date
printDifference(date1, date2);
} catch (ParseException e) {
e.printStackTrace();
}
}
public void printDifference(Date startDate, Date endDate) {
long different = endDate.getTime() - startDate.getTime();
System.out.println("startDate : " + startDate);
System.out.println("endDate : "+ endDate);
System.out.println("different : " + different);
long secondsInMilli = 1000;
long minutesInMilli = secondsInMilli * 60;
long hoursInMilli = minutesInMilli * 60;
long daysInMilli = hoursInMilli * 24;
long elapsedDays = different / daysInMilli;
different = different % daysInMilli;
long elapsedHours = different / hoursInMilli;
different = different % hoursInMilli;
long elapsedMinutes = different / minutesInMilli;
different = different % minutesInMilli;
long elapsedSeconds = different / secondsInMilli;
System.out.printf(
"%d days, %d hours, %d minutes, %d seconds%n",
elapsedDays,
elapsedHours, elapsedMinutes, elapsedSeconds);
}
Upvotes: 0
Views: 96
Reputation: 521249
The pattern you used when constructing your SimpleDateFormat
has a problem. You used this:
yyyy/mm/dd hh:mm:ss
But you should have used this:
yyyy/MM/dd hh:mm:ss
From the documentation, lowercase m
means minutes in an hour, which is appropriate for the timestamp portion of your format string, while uppercase M
means months in the year.
Upvotes: 3