Java 根据年月日获取当前年龄

港控/mmm° 2022-05-22 08:36 575阅读 0赞

主要代码

  1. public static int getAgeByBirthDay(String birthDay){
  2. if (birthDay == null || birthDay.length()<4) {
  3. return 0;
  4. }
  5. SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
  6. //得到当前的年份
  7. String cYear = sdf.format(new Date()).substring(0,4);
  8. String cMouth = sdf.format(new Date()).substring(5,7);
  9. String cDay = sdf.format(new Date()).substring(8,10);
  10. //得到生日年份
  11. String birth_Year = birthDay .substring(0,4);
  12. String birth_Mouth = birthDay .substring(5,7);
  13. String birth_Day = birthDay .substring(8,10);
  14. //年月日比较后得到年龄
  15. int age = Integer.parseInt(cYear) - Integer.parseInt(birth_Year);
  16. if ((Integer.parseInt(cMouth) - Integer.parseInt(birth_Mouth))<0) {
  17. age=age-1;
  18. }else if ((Integer.parseInt(cMouth) - Integer.parseInt(birth_Mouth))==0) {
  19. if ( (Integer.parseInt(cDay) - Integer.parseInt(birth_Day))>0) {
  20. age=age-1;
  21. }else {
  22. age = Integer.parseInt(cYear) - Integer.parseInt(birth_Year);
  23. }
  24. }else if ((Integer.parseInt(cMouth) - Integer.parseInt(birth_Mouth))>0) {
  25. age = Integer.parseInt(cYear) - Integer.parseInt(birth_Year);
  26. }
  27. return age;
  28. }

发表评论

表情:
评论列表 (有 0 条评论,575人围观)

还没有评论,来说两句吧...

相关阅读