package cn.bdqn.smbms.util;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* 此为工具类,数据转换等
* @author 小0
*/
public class Tools {
/**
* 计算某人的生日到当前一共有几个闰年,此方法是为了更精确考虑闰年,从而计算出生日。
* @param data 数据库传入的生日
*/
public static int getLY(String data){
int leapYear = 0;
if(!("".equals(data))) {
SimpleDateFormat myFormat = new SimpleDateFormat("yyyy");
Date date = new Date();
int birthYear = Integer.parseInt(data.substring(0, 4)); //获取出生日期,解析为Date类型
int currYear = Integer.parseInt(myFormat.format(date)); //获取当前日期
for(int year=birthYear;year<=currYear;year++) {
if((year%4==0 && year%100!=0)||(year%400==0)) {
leapYear++ ;//从出生年到当前年,只有是闰年就+1
}
}
}
return leapYear;
}
/**
* 通过生日减去当前日期求年龄。
* @param data 接收数据库传来的birthDate:1980-08-09
* @return 返回年龄
*/
public static int transToAge(String data) throws Exception {
int age = 0;
long leapYear = (long)getLY(data);//其实会自动转成int
if(!("".equals(data))) {
SimpleDateFormat myFormat = new SimpleDateFormat("yyyy-MM-dd");
Date date = new Date();
Date birthDate = myFormat.parse(data);//获取出生日期,解析为Date类型
Date currDate = myFormat.parse(myFormat.format(date)); //获取当前日期
if(birthDate.getTime()<=currDate.getTime()) { //以来此Date 对象表示的毫秒数
age = (int)(((currDate.getTime()-birthDate.getTime())/(24*60*60*1000)-leapYear)/365);
//365L表示长整型
}
}
return age;
}
}