Java生日计算年龄工具
package com.web.backend.util;
import java.util.Calendar;
import java.util.Date;
/**
* @Author: SongZS
* @Description: 通过生日获取年龄计算工具
* @Date: Created in 18:23 2018/8/16
* @Modified By:
*/
public class GetAgeByBirthdayUtil {
public static int getAgeByBirthday(Date birthday) {
int age = 0;
try {
Calendar calendar= Calendar.getInstance();
calendar.setTime(new Date());
Calendar birthday = Calendar.getInstance();
birthday.setTime(birthday);
if (birthday.after(calendar)) {
age = 0;
} else {
age = calendar.get(Calendar.YEAR) - birthday.get(Calendar.YEAR);
if (calendar.get(Calendar.DAY_OF_YEAR) > birthday.get(Calendar.DAY_OF_YEAR)) {
age += 1;
}
}
return age;
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}
}
使用
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Date bithday = format.parse("Birthday"); int age = GetAgeByBirthUtil.getAgeByBirthday(bithday); System.out.println(age);