public class TimeUtil {
/**
* 根据年月日计算年龄,birthTimeString "1994-11-14"
* @param birthTimeString
* @return
*/
public static int getAgeByBirthTime(String birthTimeString) {
String strs[] = birthTimeString.trim().split("-");
int selectYear = Integer.parseInt(strs[0]);
int selectMonth = Integer.parseInt(strs[1]);
int selectDay = Integer.parseInt(strs[2]);
Calendar cal = Calendar.getInstance();
int yearNow = cal.get(Calendar.YEAR);
int monthNow = cal.get(Calendar.MONTH) + 1;
int dayNow = cal.get(Calendar.DATE);
int yearMinus = yearNow - selectYear;
int monthMinus = monthNow - selectMonth;
int dayMinus = dayNow - selectDay;
int age = yearMinus;
if (yearMinus < 0) {
age = 0;
} else if (yearMinus == 0) {
if (monthMinus < 0) {
age = 0;
} else if (monthMinus == 0) {
if (dayMinus < 0) {
age = 0;
} else if (dayMinus >= 0) {
age = 1;
}
} else if (monthMinus > 0) {
age = 1;
}
} else if (yearMinus > 0) {
if (monthMinus < 0) {
} else if (monthMinus == 0) {
if (dayMinus < 0) {
} else if (dayMinus >= 0) {
age = age + 1;
}
} else if (monthMinus > 0) {
age = age + 1;
}
}
return age;
}
/**
* 根据时间戳计算年龄
* @param birthTime
* @return
*/
public static int getAgeByBirthTime(long birthTime) {
Date date = new Date(birthTime * 1000l);
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
String birthTimeString = format.format(date);
return getAgeByBirthTime(birthTimeString);
}
/**
* 字符串转 Date类型
* @param stringTime 2000-01-01 06:00:00
* @return
*/
public static Date stringToDate(String stringTime) {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
try {
return simpleDateFormat.parse(stringTime);
} catch (ParseException e) {
e.printStackTrace();
return null;
}
}
/**
* 获取当前时间一周后时间
* @return
*/
public static Date getDateOfAWeekLate() {
Calendar curr = Calendar.getInstance();
curr.set(Calendar.DAY_OF_MONTH, curr.get(Calendar.DAY_OF_MONTH) + 7);
Date date = curr.getTime();
return date;
}
/**
* 获取当前时间一月后时间
* @return
*/
public static Date getDateOfAMonthLate() {
Calendar curr = Calendar.getInstance();
curr.set(Calendar.MONTH, curr.get(Calendar.MONTH) + 1);
Date date = curr.getTime();
return date;
}
/**
* 获取当前时间一年后时间
* @return
*/
public static Date getDateOfAyearLate() {
Calendar curr = Calendar.getInstance()
curr.set(Calendar.YEAR, curr.get(Calendar.YEAR) + 1);
Date date = curr.getTime();
return date;
}
/**
* 获取当天开始时间
* @return
*/
public static Date todayZero() {
long current = System.currentTimeMillis(); //当前时间毫秒数
long zero = current/(1000*3600*24)*(1000*3600*24) - TimeZone.getDefault().getRawOffset(); //今天零点零分零秒的毫秒数
Date date = new Date(zero);
return date;
}
/**
* 获取当天结束时间
* @return
*/
public static Date todayEnd() {
long current = System.currentTimeMillis(); //当前时间毫秒数
long zero = current/(1000*3600*24)*(1000*3600*24) - TimeZone.getDefault().getRawOffset(); //今天零点零分零秒的毫秒数
long end = zero + 24*60*60*1000-1; //今天23点59分59秒的毫秒数
Date date = new Date(end);
return date;
}
TimeUtil 时间工具类——随时更新
最新推荐文章于 2023-02-27 17:58:30 发布