Reputation: 3127
I want to find the date difference in month and days between two dates. One is my system current date and another is in the future.
and the future date is in this format:
2014-02-06 21:26
I have used below code to find the difference.
1.
currentCal = Calendar.getInstance();
weddingCal = Calendar.getInstance();
weddingCal.clear();
DateFormat formatterResponseDate = new SimpleDateFormat("yyyy-MM-dd HH:mm");
formatterResponseDate.setTimeZone(TimeZone.getTimeZone("GMT"));
weddingCal.setTime(formatterResponseDate.parse(responseThis.trim()));
long dateDiff = weddingCal.getTimeInMillis() -
currentCal.getTimeInMillis();
long months = dateDiff / (30 * 24 * 60 * 60 * 1000);
long days = (dateDiff % (30 * 24 * 60 * 60 * 1000)) / (24 * 60 * 60 * 1000);
But it gives me wrong result and I think it's not convenient because sometimes there are 31 days in a month. I have also used JODA - Time to find the difference, but it also does not help me.
2.
currentCal = Calendar.getInstance();
startDate = new DateTime(currentCal.get(Calendar.YEAR),
(currentCal.get(Calendar.MONTH)+1),
currentCal.get(Calendar.DAY_OF_MONTH), currentCal.get(Calendar.HOUR),
currentCal.get(Calendar.MINUTE));
weddingCal = Calendar.getInstance();
weddingCal.clear();
weddingCal.setTime(formatterResponseDate.parse(responseThis.trim()));
endDate = new DateTime(weddingCal.get(Calendar.YEAR), (weddingCal.get(Calendar.MONTH)+1),
weddingCal.get(Calendar.DAY_OF_MONTH), weddingCal.get(Calendar.HOUR),
weddingCal.get(Calendar.MINUTE));
Period period = new Period(startDate, endDate);
tvMonth.setText(String.valueOf(period.getMonths()));
tvDays.setText(String.valueOf(period.getDays()));
Both are not working please help me, how Can I find it? Thanks
Upvotes: 3
Views: 3752
Reputation: 3127
I have used the below code and it works fine.
currentCal = Calendar.getInstance();
startDate = new DateTime(currentCal.get(Calendar.YEAR),
(currentCal.get(Calendar.MONTH)+1),
currentCal.get(Calendar.DAY_OF_MONTH),
currentCal.get(Calendar.HOUR),
currentCal.get(Calendar.MINUTE));
weddingCal = Calendar.getInstance();
weddingCal.clear();
weddingCal.setTime(formatterResponseDate.parse(responseThis.trim()));
endDate = new DateTime(weddingCal.get(Calendar.YEAR),
(weddingCal.get(Calendar.MONTH)+1),
weddingCal.get(Calendar.DAY_OF_MONTH),
weddingCal.get(Calendar.HOUR),
weddingCal.get(Calendar.MINUTE));
Period period = new Period(startDate, endDate, PeriodType.yearMonthDayTime());
tvMonth.setText(String.valueOf(period.getMonths()));
tvDays.setText(String.valueOf(period.getDays()));
Upvotes: 4