由网友(耍酷是爷的资本)分享简介:我试图从特定日期确定年龄多年。有谁知道一个干净的方式来做到这一点在Android中?我有Java的API可很明显,但在直线上升Java API是pretty的软弱,我希望Android有一些东西来帮助我。编辑:多项建议使用乔达时间的Android让我担心了一下,由于 Android的Java的 - 乔达日期缓慢和有...
我试图从特定日期确定年龄多年。有谁知道一个干净的方式来做到这一点在Android中?我有Java的API可很明显,但在直线上升Java API是pretty的软弱,我希望Android有一些东西来帮助我。
编辑:多项建议使用乔达时间的Android让我担心了一下,由于 Android的Java的 - 乔达日期缓慢和有关的问题。此外,拉动不附带平台库的东西,这个规模可能是矫枉过正。
解决方案 公共静态INT getDiffYears(日期第一,最后的日期){
日历一= getCalendar(第一);
日历B = getCalendar(最后一个);
INT差异= b.get(YEAR) - a.get(年);
如果(a.get(月)GT; b.get(月)||
(a.get(月)== b.get(月)及和放大器; a.get(DATE)> b.get(DATE))){
diff--;
}
返回差异;
}
公共静态日历getCalendar(日期日期){
日历CAL = Calendar.getInstance(Locale.US);
cal.setTime(日期);
返回CAL;
}
I am trying to determine an age in years from a certain date. Does anyone know a clean way to do this in Android? I have the Java api available obviously, but the straight-up java api is pretty weak, and I was hoping that Android has something to help me out.
EDIT: The multiple recommendations to use Joda time in Android worries me a bit due to Android Java - Joda Date is slow and related concerns. Also, pulling in a library not shipped with the platform for something this size is probably overkill.
解决方案public static int getDiffYears(Date first, Date last) {
Calendar a = getCalendar(first);
Calendar b = getCalendar(last);
int diff = b.get(YEAR) - a.get(YEAR);
if (a.get(MONTH) > b.get(MONTH) ||
(a.get(MONTH) == b.get(MONTH) && a.get(DATE) > b.get(DATE))) {
diff--;
}
return diff;
}
public static Calendar getCalendar(Date date) {
Calendar cal = Calendar.getInstance(Locale.US);
cal.setTime(date);
return cal;
}
相关推荐
最新文章