| | |
| | | import java.text.DateFormat; |
| | | import java.text.ParseException; |
| | | import java.text.SimpleDateFormat; |
| | | import java.time.LocalDateTime; |
| | | import java.util.ArrayList; |
| | | import java.util.Calendar; |
| | | import java.util.Date; |
| | |
| | | } |
| | | return um; |
| | | } |
| | | |
| | | /** |
| | | * 根据单位计算目标日期 |
| | | * |
| | | * @param num 距离 |
| | | * @param unit 日期单位 Y/M/D |
| | | * @return |
| | | */ |
| | | public static Date calDate(Integer num, String unit) { |
| | | Calendar calendar = Calendar.getInstance(); |
| | | Date targetDate = null; |
| | | switch (unit) { |
| | | case "Y": |
| | | calendar.add(Calendar.YEAR, num); |
| | | targetDate = calendar.getTime(); |
| | | break; |
| | | case "M": |
| | | calendar.add(Calendar.MONTH, num); |
| | | targetDate = calendar.getTime(); |
| | | break; |
| | | case "D": |
| | | calendar.add(Calendar.DAY_OF_MONTH, num); |
| | | targetDate = calendar.getTime(); |
| | | break; |
| | | default: |
| | | targetDate = stringToDate("9999-12-31", DATE_FORMAT_DD); |
| | | |
| | | } |
| | | |
| | | return targetDate; |
| | | } |
| | | |
| | | public static String getAgeForBirthDay(Date birthDay) { |
| | | Calendar cal = Calendar.getInstance(); |
| | | if (birthDay == null) { |
| | | return "-"; |
| | | } |
| | | // 出生日期晚于当前时间,无法计算 |
| | | if (cal.before(birthDay)) { |
| | | return "-"; |
| | | } |
| | | // 当前年份 |
| | | int yearNow = cal.get(Calendar.YEAR); |
| | | // 当前月份 |
| | | int monthNow = cal.get(Calendar.MONTH); |
| | | // 当前日期 |
| | | int dayOfMonthNow = cal.get(Calendar.DAY_OF_MONTH); |
| | | cal.setTime(birthDay); |
| | | int yearBirth = cal.get(Calendar.YEAR); |
| | | int monthBirth = cal.get(Calendar.MONTH); |
| | | int dayOfMonthBirth = cal.get(Calendar.DAY_OF_MONTH); |
| | | // 计算整岁数 |
| | | Integer age = yearNow - yearBirth; |
| | | if (monthNow <= monthBirth) { |
| | | if (monthNow == monthBirth) { |
| | | if (dayOfMonthNow < dayOfMonthBirth) { |
| | | // 当前日期在生日之前,年龄减一 |
| | | age--; |
| | | } |
| | | } else { |
| | | age--; |
| | | } |
| | | } |
| | | |
| | | return age.toString(); |
| | | } |
| | | } |