/**
* 获取 2 个时间的自然年历的时间间隔
*
* @param nextDate 后面的时间,需要大于 previousDate
* @param previousDate 前面的时间
*/
private String getTimeInterval(Calendar nextDate, Calendar previousDate) {
int year = nextDate.get(Calendar.YEAR) - previousDate.get(Calendar.YEAR);
int month = nextDate.get(Calendar.MONTH) - previousDate.get(Calendar.MONTH);
int day = nextDate.get(Calendar.DAY_OF_MONTH) - previousDate.get(Calendar.DAY_OF_MONTH);
int hour = nextDate.get(Calendar.HOUR_OF_DAY) - previousDate.get(Calendar.HOUR_OF_DAY);// 24小时制
int min = nextDate.get(Calendar.MINUTE) - previousDate.get(Calendar.MINUTE);
int second = nextDate.get(Calendar.SECOND) - previousDate.get(Calendar.SECOND);
boolean hasBorrowDay = false;// "时"是否向"天"借过一位
if (second < 0) {
second += 60;
min--;
}
if (min < 0) {
min += 60;
hour--;
}
if (hour < 0) {
hour += 24;
day--;
hasBorrowDay = true;
}
if (day < 0) {
// 计算截止日期的上一个月有多少天,补上去
Calendar tempDate = (Calendar) nextDate.clone();
tempDate.add(Calendar.MONTH, -1);// 获取截止日期的上一个月
day += tempDate.getActualMaximum(Calendar.DAY_OF_MONTH);
// nextDate是月底最后一天,且day=这个月的天数,即是刚好一整个月,比如20160131~20160229,day=29,实则为1个月
if (!hasBorrowDay
&& nextDate.get(Calendar.DAY_OF_MONTH) == nextDate.getActualMaximum(Calendar.DAY_OF_MONTH)// 日期为月底最后一天
&& day >= nextDate.getActualMaximum(Calendar.DAY_OF_MONTH)) {// day刚好是nextDate一个月的天数,或大于nextDate月的天数(比如2月可能只有28天)
day = 0;// 因为这样判断是相当于刚好是整月了,那么不用向 month 借位,只需将 day 置 0
} else {// 向month借一位
month--;
}
}
if (month < 0) {
month += 12;
year--;
}
String timeStr = "";
if (year > 0) timeStr += year + "年";
if (month > 0) timeStr += month + "月";
if (day > 0) timeStr += day + "天";
return timeStr;
}
/**
* 根据出生年月计算年龄
*
* @param birthday 出生年月
* yyyy
* yyyy-MM
* yyyy-MM-dd
* @return age
*/
private static Integer getAgeByBirthday(String birthday) {
if ("".equals(birthday) || birthday == null) {
return null;
}
// System.out.println("birthday>>>" + birthday);
// 此处调用了获取当前日期,以yyyy-MM-dd格式返回的日期字符串方法
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String nowDate = sdf.format(new Date());
// 当前时间
String[] nowDates = nowDate.split("-");
// 分割时间线 - 年[0],月[1],日[2]
String[] dates = birthday.split("-");
// 年龄默认为当前时间和生日相减
int age = Integer.parseInt(nowDates[0]) - Integer.parseInt(dates[0]);
// 根据月推算出年龄是否需要增加
if (dates.length >= 2) {
// 如果当前月份大于生日月份,岁数不变,否则加一
Integer nowMonth = Integer.parseInt(nowDate.substring(5, 7));
Integer birthMonth = Integer.parseInt(birthday.substring(5, 7));
if (nowMonth < birthMonth)
age++;
// 月份相同才计算对应年龄
if (dates.length >= 3 && nowMonth.equals(birthMonth)) {
// 如果天数大于当前生日月份,岁数不变,否则加一
// 当前天数
Integer nowDay = Integer.parseInt(nowDates[2]);
// 生日天数
Integer birDay = Integer.parseInt(dates[2]);
if (nowDay < birDay)
age++;
}
}
return age;
}