正在显示
1 个修改的文件
包含
39 行增加
和
0 行删除
@@ -31,6 +31,8 @@ public final class DateUtil { | @@ -31,6 +31,8 @@ public final class DateUtil { | ||
31 | 31 | ||
32 | public static String F8 = "yyyyMMdd"; | 32 | public static String F8 = "yyyyMMdd"; |
33 | 33 | ||
34 | + public static String F6 = "yyyyMM"; | ||
35 | + | ||
34 | public static String[] dataStringFormats = {F8, F10, F14, F19, "yyyy/MM/dd", "yyyy/MM/dd HH:mm", "yyyy/MM/dd HH:mm:ss", "yyyy-MM-dd HH:mm"}; | 36 | public static String[] dataStringFormats = {F8, F10, F14, F19, "yyyy/MM/dd", "yyyy/MM/dd HH:mm", "yyyy/MM/dd HH:mm:ss", "yyyy-MM-dd HH:mm"}; |
35 | 37 | ||
36 | private static Date currentDate = new Date(); | 38 | private static Date currentDate = new Date(); |
@@ -445,4 +447,41 @@ public final class DateUtil { | @@ -445,4 +447,41 @@ public final class DateUtil { | ||
445 | Instant instant = localDateTime.atZone(zone).toInstant(); | 447 | Instant instant = localDateTime.atZone(zone).toInstant(); |
446 | java.util.Date date = Date.from(instant); | 448 | java.util.Date date = Date.from(instant); |
447 | } | 449 | } |
450 | + | ||
451 | + /** | ||
452 | + * 根据出生日期计算年龄 | ||
453 | + * @param birthDay | ||
454 | + * @return | ||
455 | + * @throws ParseException | ||
456 | + */ | ||
457 | + public static int getAgeByBirth(Date birthDay) throws ParseException { | ||
458 | + int age = 0; | ||
459 | + Calendar cal = Calendar.getInstance(); | ||
460 | + //出生日期晚于当前时间,无法计算 | ||
461 | + if (cal.before(birthDay)) { | ||
462 | + throw new IllegalArgumentException( | ||
463 | + "The birthDay is before Now.It's unbelievable!"); | ||
464 | + } | ||
465 | + //当前年份 | ||
466 | + int yearNow = cal.get(Calendar.YEAR); | ||
467 | + //当前月份 | ||
468 | + int monthNow = cal.get(Calendar.MONTH); | ||
469 | + //当前日期 | ||
470 | + int dayOfMonthNow = cal.get(Calendar.DAY_OF_MONTH); | ||
471 | + cal.setTime(birthDay); | ||
472 | + int yearBirth = cal.get(Calendar.YEAR); | ||
473 | + int monthBirth = cal.get(Calendar.MONTH); | ||
474 | + int dayOfMonthBirth = cal.get(Calendar.DAY_OF_MONTH); | ||
475 | + //计算整岁数 | ||
476 | + age = yearNow - yearBirth; | ||
477 | + if (monthNow <= monthBirth) { | ||
478 | + if (monthNow == monthBirth) { | ||
479 | + //当前日期在生日之前,年龄减一 | ||
480 | + if (dayOfMonthNow < dayOfMonthBirth){ age--;} | ||
481 | + } else { | ||
482 | + age--;//当前月份在生日之前,年龄减一 | ||
483 | + } | ||
484 | + } | ||
485 | + return age; | ||
486 | + } | ||
448 | } | 487 | } |
-
请 注册 或 登录 后发表评论