Android由出生年月日计算年龄(周岁)
先从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 }
posted on 2019-09-11 19:49 ken9527just 阅读(3235) 评论(0) 编辑 收藏 举报