这个小的库是之前自己写Project的时候编的,经常会用,决定Share一下,希望对大家有用~~
先介绍一下有什么函数:
- 根据两个Calendar计算岁数
- 根据生日的Long值计算岁数
- 把Calendar形式的时间转换成Long
- 把Date形式的时间转换成Long
- 判断输入的年月日是否合法(含闰年的相关内容)
- 时间格式转换类——Long->“yyyy-MM-dd hh:mm:ss”
- 匹配生日和身份证号是否相符
- 基于身份证号,生成Long类型的生日
然后呢,直接放代码吧——————(注释应该是比较详细的了)
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
/**
* 时间处理类
*/
public class TimeCalculator {
//工具类,不允许被实例化
private TimeCalculator(){}
/**
* 根据两个时间计算岁数
* @param nowTime
* @param oldTime
* @return
*/
public static int calculateAge(Calendar nowTime, Calendar oldTime) {
int age = nowTime.get(Calendar.YEAR) - oldTime.get(Calendar.YEAR);
if (nowTime.get(Calendar.MONTH) 28) {
return false;
}
}
return true;
}
/**
* 判断输入的年月日是否合法
* 比如说,2000.02.31不合理
* @param time
* @return
*/
public static boolean judgeDate(Calendar time) {
int year = time.get(Calendar.YEAR);
int month = time.get(Calendar.MONTH);
int day = time.get(Calendar.DATE);
if (judgeIsLeapYear(year) && judgeLeapYearDate(month, day)) {
return true;
} else if (!judgeIsLeapYear(year) && judgeNonLeapYearDate(month, day)) {
return true;
}
return false;
}
/**
* 时间格式转换类
* Long->"yyyy-MM-dd hh:mm:ss"
* @param time
* @return
*/
public static String transformTime(Long time){
Date d = new Date(time);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
return sdf.format(d);
}
/**
* 匹配生日和身份证号是否相符
* @param birthday
* @param idNumber
* @return
*/
public static boolean matchIdAndBirthday(Long birthday, String idNumber) {
//还是先排空
if (idNumber == null || birthday == null) {
return false;
}
//小心:从0开始的+左闭右开
//年份在第7-10位,索引是6-9
String year = idNumber.substring(6, 10);
//月份在第11-12位,索引是10-11
String month = idNumber.substring(10, 12);
//日期在第13-14位,索引是12-13
String day = idNumber.substring(12, 14);
//转换时间
Calendar time = Calendar.getInstance();
time.setTime(new Date(birthday));
//读取年月日
Integer yearInt = time.get(Calendar.YEAR);
Integer monthInt = time.get(Calendar.MONTH);
Integer dayInt = time.get(Calendar.DATE);
//转换成String,防止身份证报异常
String yearStr = yearInt.toString();
String monthStr = monthInt.toString();
String dayStr = dayInt.toString();
//年月日都要匹配
if (year.equals(yearStr) && month.equals(monthStr) && day.equals(dayStr)) {
return true;
}
return false;
}
/**
* 基于身份证号,生成Long类型的生日
* @param idNumber
* @return
*/
public static Long generateLongBirthdayById(String idNumber) {
//还是先排空
if (idNumber == null) {
return null;
}
//小心:从0开始的+左闭右开
//年份在第7-10位,索引是6-9
Integer year = Integer.parseInt(idNumber.substring(6, 10));
//月份在第11-12位,索引是10-11
Integer month = Integer.parseInt(idNumber.substring(10, 12));
//日期在第13-14位,索引是12-13
Integer date = Integer.parseInt(idNumber.substring(12, 14));
//转换时间
Calendar birthday = Calendar.getInstance();
//小心月份从0起
birthday.set(year, --month, date);
return birthday.getTimeInMillis();
}
}