如何在Android中获取并显示自约会以来的天数,月数和年数?
例如,假设前一个日期是:
02/02/2017
今天的日期是:
04/30/2018
我希望它能说:
1 year, 2 months, 28 days
我想我需要得到这样的总天数:
long msDiff = Calendar.getInstance().getTimeInMillis() - oldCalendarDate.getTimeInMillis();
long daysDiff = TimeUnit.MILLISECONDS.toDays(msDiff);
但如何将天数转换为年,月和日的清晰度?请记住,并非所有月份都有31天。
因为这样,我才得到
452 days
结果。但我希望它更像是1年,2个月,28天。
有更好的解决方案吗?
另外,我想在变量中得到旧日期:
val oldCalendarDate = GregorianCalendar(2017, 3, 30).time
但是上述代码根本无法正常工作。是的,我知道变量在kotlin中,因为我在kotlin工作,所以请原谅语法。我认为更多的问题是如何格式化整数。我已经将其他java代码转换为kotlin,但我将其发布为java帖子,因为更多人熟悉java。
答案 0 :(得分:1)
Calendar
对象可以解决此问题
val msDiff = Calendar.getInstance().timeInMillis - oldCalendarDate.timeInMillis;
val calDiff = Calendar.getInstance()
calDiff.timeInMillis = msDiff
val msg = "${calDiff.get(Calendar.YEAR) - 1970} year, ${calDiff.get(Calendar.MONTH)} months, $calDiff.get(Calendar.DAY_OF_MONTH)} days"
答案 1 :(得分:0)
你试试这段代码,
long different = your today date - your previous date;
// take both dates in date format.
long secondsInMilli = 1000;
long minutesInMilli = secondsInMilli * 60;
long hoursInMilli = minutesInMilli * 60;
long daysInMilli = hoursInMilli * 24;
long mothsInMilli = daysInMilli * 30;
long yearInMilli = mothsInMilli * 12;
long elapsedYear = different / yearInMilli;
different = different % yearInMilli;
long diffYear = elapsedYear;
Log.d("", "difference of years : " + diffYear);
long elapsedMonths = different / mothsInMilli;
different = different % mothsInMilli;
long diffMonth = elapsedMonths;
Log.d("", "difference of Months : " + diffMonth);
long elapsedDays = different / daysInMilli;
different = different % daysInMilli;
long diffDays = elapsedDays;
Log.d("", "difference of Days : " + diffDays);
使用此代码我得到了适当的区别,它也可以帮助你。在下面显示,我有两个日期:
<强> pastdate :: 强> Mon Mar 26 13:06:52 GMT+05:30 2018
<强> todayDate :: 强> Mon Apr 30 13:06:52 GMT+05:30 2018
我得到了如下月份,年份和日期的差异: -
difference of Years : 0
difference of Months : 1
difference of Days : 4