package com.stylefeng.guns.modular.system.util;
|
|
import com.stylefeng.guns.core.util.DateUtil;
|
|
import java.text.ParseException;
|
import java.text.SimpleDateFormat;
|
import java.util.Calendar;
|
import java.util.Date;
|
import java.util.TimeZone;
|
|
//日期转换年龄
|
public class DataUtil {
|
|
private static TimeZone tz = TimeZone.getTimeZone("GMT+8");
|
|
public static int getAge(Date dateOfBirth) {
|
|
int age = 0;
|
|
Calendar born = Calendar.getInstance();
|
|
Calendar now = Calendar.getInstance();
|
|
if (dateOfBirth != null) {
|
|
now.setTime(new Date());
|
|
born.setTime(dateOfBirth);
|
|
if (born.after(now)) {
|
return age;
|
// throw new IllegalArgumentException("年龄不能超过当前日期");
|
}
|
age = now.get(Calendar.YEAR) - born.get(Calendar.YEAR);
|
|
int nowDayOfYear = now.get(Calendar.DAY_OF_YEAR);
|
|
int bornDayOfYear = born.get(Calendar.DAY_OF_YEAR);
|
|
// logger.debug("nowDayOfYear:" + nowDayOfYear + " bornDayOfYear:" + bornDayOfYear);
|
|
if (nowDayOfYear < bornDayOfYear) {
|
|
age -= 1;
|
}
|
|
}
|
|
return age;
|
|
}
|
/**
|
* 字符串日期转Date yyyy-MM-dd HH:mm:ss
|
*
|
* @param
|
* @return
|
*/
|
public static Date getDate_str3(String dateStr) {
|
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
|
sdf.setTimeZone(tz);
|
if ("".equals(dateStr)) {
|
dateStr = sdf.format(DateUtil.getDate());
|
}
|
Date date = null;
|
try {
|
date = sdf.parse(dateStr);
|
} catch (ParseException e) {
|
e.printStackTrace();
|
}
|
return date;
|
}
|
|
|
/**
|
* 日期转毫秒
|
*
|
* @param date
|
* @return
|
*/
|
public static long getMillisecond(Date date) {
|
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
|
String newDate = "";
|
if (!"".equals(date)) {
|
newDate = sdf.format(date);
|
} else {
|
newDate = sdf.format(DateUtil.getDate());
|
}
|
long millisecond = 0;
|
try {
|
millisecond = sdf.parse(newDate).getTime();
|
} catch (ParseException e) {
|
e.printStackTrace();
|
}
|
return millisecond;
|
}
|
|
/**
|
* 两日期相差天数
|
*
|
* @param startDate
|
* @param endDate
|
* @return
|
*/
|
public static long getMinusDay(Date startDate, Date endDate) {
|
long startMillisecond = getMillisecond(startDate);
|
long endMillisecond = getMillisecond(endDate);
|
long minusMillisecond = endMillisecond - startMillisecond;
|
long day = 0;
|
if (minusMillisecond < 0) {
|
day = 0;
|
} else {
|
day = minusMillisecond / (24 * 3600 * 1000);
|
}
|
return day;
|
}
|
|
|
|
|
}
|