思路
- 獲取Date類型的生日,之后轉換成毫秒,再把當前的毫秒數相減就可以獲得到用戶活了多少毫秒,再把毫秒轉換成天轉換成年即可,可能需要處理一下閏年的情況
- 獲取Date類型的生日,轉換成Calendar,把當前時間也轉成Calendar之后獲取兩者Calendar.YEAR,兩者相減,之后判斷生日的Calendar.DAY_OF_YEAR是否大于當前時間,如果大于說明還沒有到今年的生日,剛剛算出來的年齡要減一
實現
1.轉換毫秒(沒有處理閏年的)
String dateStr = "1999-1-1";
Date date = Date.valueOf(dateStr);
Date now = new Date(System.currentTimeMillis());
//相差天數
int day = (int)((now.getTime()-date.getTime()) / (1000 * 60 * 60 * 24));
System.out.println("年齡=" + (day / 365));
2.使用Calendar
String dateStr = "1999-1-1"; //生日
Date date = Date.valueOf(dateStr);
Calendar now = Calendar.getInstance();
Calendar birth = Calendar.getInstance();
birth.setTime(date);
int age = 0;
if(birth.after(now)) {
//當生日在當前時間的前面的時候->這是不可能的
} else {
age = now.get(Calendar.YEAR) - birth.get(Calendar.YEAR);
if(now.get(Calendar.DAY_OF_YEAR) < birth.get(Calendar.DAY_OF_YEAR)) {
age -= 1;
}
}
System.out.println("年齡=" + age);
個人比較推薦第二種方法,比較直接而且日期計算一般都不直接用Date相關的方法的。