2021-12-20 12:37:55
浏览数 (1)
目录
工具类
代码语言:javascript
复制public class DateUtil {
//将 格式为 yyyy-MM-dd字符串类型的 时间 转为 Date类型
public static Date parse(String strDate) throws ParseException {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
return sdf.parse(strDate);
}
// 根据出生日期 获取 到年龄
public static String getAge(String date) {
try {
Date birthDay = parse(date);
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--;//当前月份在生日之前,年龄减一
}
} return age "";
}catch (Exception e){
}
return "未知";
}
/**
* 判断时间是否在时间段内
*
* @param nowTime
* @param beginTime
* @param endTime
* @return
*/
public static boolean belongCalendar(Date nowTime, Date beginTime,
Date endTime) {
Calendar date = Calendar.getInstance();
date.setTime(nowTime);
Calendar begin = Calendar.getInstance();
begin.setTime(beginTime);
Calendar end = Calendar.getInstance();
end.setTime(endTime);
if (date.after(begin) && date.before(end)) {
return true;
} else {
return false;
}
}
/**
* isodate时间格式转换
* @param datetime Thu Jul 29 22:31:27 CST 2010
* @return
*/
public static String getISODateStr(String datetime){
SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy", java.util.Locale.US);
Date date = null;
try {
date = sdf.parse(datetime);
} catch (ParseException e) {
e.printStackTrace();
}
String newDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(date);
return newDate;
}