Android 計算出生日期至今天數(獲取寶寶出生到現在天數)
阿新 • • 發佈:2018-12-30
data和nowTime格式為:2018-8-24 可以通過SimpleDateFormat.format 得到
public static String getAge(String date, String nowTime) { if (TextUtils.isEmpty(date)||TextUtils.isEmpty(nowTime)){ return ""; } String[] data = date.split("-"); String[] nowData = nowTime.split("-"); if (data.length < 3 || nowData.length < 3) return ""; Calendar birthday = new GregorianCalendar(Integer.valueOf(data[0]), Integer.valueOf(data[1]), Integer.valueOf(data[2])); Calendar now = new GregorianCalendar(Integer.valueOf(nowData[0]), Integer.valueOf(nowData[1]), Integer.valueOf(nowData[2])); int day = now.get(Calendar.DAY_OF_MONTH) - birthday.get(Calendar.DAY_OF_MONTH); int month = now.get(Calendar.MONTH) - birthday.get(Calendar.MONTH); int year = now.get(Calendar.YEAR) - birthday.get(Calendar.YEAR); // 按照減法原理,先day相減,不夠向month借;然後month相減,不夠向year借;最後year相減。 if (day < 0) { month -= 1; now.add(Calendar.MONTH, -1);// 得到上一個月,用來得到上個月的天數。 day = day + now.getActualMaximum(Calendar.DAY_OF_MONTH); } if (month < 0) { month = (month + 12) % 12; year--; } System.out.println("年齡:" + year + "歲" + month + "月" + day + "天"); StringBuffer tag = new StringBuffer(); if (year > 0) { tag.append(year + "歲"); } if (month > 0) { tag.append(month + "個月"); } if (day > 0) { tag.append(day + "天"); } if (year == 0 && month == 0 && day == 0) { tag.append("今日出生"); } return String.valueOf(tag); }