android-查找两个日期之间的月份和日期差异
作者:互联网
我想找到两个日期之间月份和日期的日期差异.一个是我系统的当前日期,另一个是将来的日期.
未来日期采用以下格式:
2014-02-06 21:26
我使用下面的代码来找到区别.
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);
但这给了我错误的结果,我认为这并不方便,因为有时一个月中有31天.我也曾使用JODA – Time来找到差异,但这也无济于事.
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()));
两者均无法正常工作,请帮助我,如何找到它?
谢谢
解决方法:
我用下面的代码,它工作正常.
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()));
标签:jodatime,calendar,datetime,android,date 来源: https://codeday.me/bug/20191030/1967991.html