我如何才能找到多年从事android的两个日期之间有多少?有多少、多年、两个、日期

2023-09-06 01:39:10 作者:耍酷是爷的资本

我试图从特定日期确定年龄多年。有谁知道一个干净的方式来做到这一点在Android中?我有Java的API可很明显,但在直线上升Java API是pretty的软弱,我希望Android有一些东西来帮助我。

编辑:多项建议使用乔达时间的Andr​​oid让我担心了一下,由于 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.

Android 10正式版什么时候上线 安卓手机有必要升级最新android版本吗

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;
}