主函数
public static int dateDiff(char flag, Calendar calSrc, Calendar calDes) {long millisDiff = getMillis(calSrc) - getMillis(calDes);if (flag == 'y') {return (calSrc.get(Calendar.YEAR) - calDes.get(Calendar.YEAR));}if (flag == 'd') {return (int) (millisDiff / DAY_IN_MILLIS);}if (flag == 'h') {return (int) (millisDiff / HOUR_IN_MILLIS);}if (flag == 'm') {return (int) (millisDiff / MINUTE_IN_MILLIS);}if (flag == 's') {return (int) (millisDiff / SECOND_IN_MILLIS);}return 0;
}
调用:
public static void main(String[] args) {Date beginDate = DateUtils.str2Date("2023-06-01 12:00:00", DateUtils.getSDFormat("yyyy-MM-dd HH:mm:ss"));Date endDate = DateUtils.str2Date("2023-06-01 14:00:00", DateUtils.getSDFormat("yyyy-MM-dd HH:mm:ss"));Calendar calendar1 = Calendar.getInstance();Calendar calendar2 = Calendar.getInstance();calendar1.setTime(beginDate);calendar2.setTime(endDate);Integer diff = DateUtils.dateDiff('h', calendar2, calendar1);System.out.println("相差小时数:" + diff.toString());beginDate = DateUtils.str2Date("2023-06-01 12:00:00", DateUtils.getSDFormat("yyyy-MM-dd HH:mm:ss"));endDate = DateUtils.str2Date("2023-06-02 14:00:00", DateUtils.getSDFormat("yyyy-MM-dd HH:mm:ss"));calendar1 = Calendar.getInstance();calendar2 = Calendar.getInstance();calendar1.setTime(beginDate);calendar2.setTime(endDate);diff = DateUtils.dateDiff('d', calendar2, calendar1);System.out.println("相差天数:" + diff.toString());}
字符转日期函数
public static Date str2Date(String str, SimpleDateFormat sdf) {if (null == str || "".equals(str)) {return null;}Date date = null;try {date = sdf.parse(str);return date;} catch (ParseException e) {e.printStackTrace();}return null;}
调用结果如下: