先從String類型的出生日期(“yyyy-MM-dd”)中提取int類型的年、月、日;再計算歲數。
程序如下:
1 /** 2 * 根據出生日期計算年齡的工具類BirthdayToAgeUtil 3 */ 4 public class BirthdayToAgeUtil { 5 6 private static String birthday; 7 private static String ageStr; 8 private static int age; 9 //出生年、月、日 10 private static int year; 11 private static int month; 12 private static int day; 13 public static String BirthdayToAge(String birthday1) { 14 birthday = birthday1; 15 stringToInt(birthday, "yyyy-MM-dd"); 16 // 得到當前時間的年、月、日 17 Calendar cal = Calendar.getInstance(); 18 int yearNow = cal.get(Calendar.YEAR); 19 int monthNow = cal.get(Calendar.MONTH) + 1; 20 int dayNow = cal.get(Calendar.DATE); 21 KLog.d("yearNow:" + yearNow); 22 KLog.d("monthNow:" + monthNow); 23 KLog.d("dayNow:" + dayNow); 24 // 用當前年月日減去出生年月日 25 int yearMinus = yearNow - year; 26 int monthMinus = monthNow - month; 27 int dayMinus = dayNow - day; 28 age = yearMinus;// 先大致賦值 29 if (yearMinus <= 0) { 30 age = 0; 31 ageStr = String.valueOf(age) + "周歲啦!"; 32 return ageStr; 33 } 34 if (monthMinus < 0) { 35 age = age - 1; 36 } else if (monthMinus == 0) { 37 if (dayMinus < 0) { 38 age = age - 1; 39 } 40 } 41 ageStr = String.valueOf(age) + "周歲啦!"; 42 return ageStr; 43 } 44 45 /** 46 * String類型轉換成date類型 47 * strTime: 要轉換的string類型的時間, 48 * formatType: 要轉換的格式yyyy-MM-dd HH:mm:ss 49 * //yyyy年MM月dd日 HH時mm分ss秒, 50 * strTime的時間格式必須要與formatType的時間格式相同 51 */ 52 private static Date stringToDate(String strTime, String formatType) { 53 KLog.d("進入stringToDate"); 54 try { 55 SimpleDateFormat formatter = new SimpleDateFormat(formatType); 56 Date date; 57 date = formatter.parse(strTime); 58 return date; 59 } catch (Exception e) { 60 return null; 61 } 62 } 63 64 /** 65 * String類型轉換為long類型 66 * ............................. 67 * strTime為要轉換的String類型時間 68 * formatType時間格式 69 * formatType格式為yyyy-MM-dd HH:mm:ss//yyyy年MM月dd日 HH時mm分ss秒 70 * strTime的時間格式和formatType的時間格式必須相同 71 */ 72 private static void stringToInt(String strTime, String formatType) { 73 KLog.d("進入stringToLong"); 74 try { 75 //String類型轉換為date類型 76 Calendar calendar = Calendar.getInstance(); 77 Date date = stringToDate(strTime, formatType); 78 calendar.setTime(date); 79 KLog.d("調用stringToDate()獲得的date:" + date); 80 if (date == null) { 81 } else { 82 //date類型轉成long類型 83 year = calendar.get(Calendar.YEAR); 84 month = calendar.get(Calendar.MONTH) + 1; 85 day = calendar.get(Calendar.DAY_OF_MONTH); 86 } 87 } catch (Exception e) { 88 KLog.d("Exception:" + e); 89 } 90 } 91 }