有JAVA如何根据年龄求出出身年月?
刚学JAVA好多不懂 苦恼!!!
[解决办法]
public static int getAge(Date birthDay) throws Exception { Calendar cal = Calendar.getInstance(); if (cal.before(birthDay)) { throw new IllegalArgumentException( "The birthDay is before Now.It's unbelievable!"); } 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); int age = yearNow - yearBirth; if (monthNow <= monthBirth) { if (monthNow == monthBirth) { if (dayOfMonthNow < dayOfMonthBirth) age--; }else{ age--; } } System.out.println("age:"+age); return age; }
[解决办法]
那就要年龄具体到月才行,比如满20周岁多3个月5天 输入 20,3,5 作为参数,这样可以推算,否则只知道周岁,只能推算出生年
for example
public static String getBirthday(int ageYear, int ageMonth, int ageDay) { Calendar c = Calendar.getInstance(); c.add(Calendar.YEAR, -ageYear); c.add(Calendar.MONTH, -ageMonth); c.add(Calendar.DAY_OF_MONTH, -ageDay); return String.format("%tF", c.getTime());}//调用String birthday = getBirthday(20, 3, 5);System.out.println(birthday);