我如何才能找到多年从事android的两个日期之间有多少? [英] How can I find the number of years between two dates in android?

查看:145
本文介绍了我如何才能找到多年从事android的两个日期之间有多少?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图从特定日期确定年龄多年。有谁知道一个干净的方式来做到这一点在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.

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

这篇关于我如何才能找到多年从事android的两个日期之间有多少?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆