1 借助hutool工具类
hutool maven依赖
cn.hutool hutool-all 5.1.0
代码实现:
System.out.println("------- year --------------");Date startDateYear = new Date(1553443200000L);Date endDateYear = new Date(System.currentTimeMillis());// 返回相差年数long betweenYear = DateUtil.betweenYear(startDateYear, endDateYear, true);System.out.println(betweenYear);System.out.println("------- month --------------");Date startDate = new Date(1553443200000L);Date endDate = new Date(System.currentTimeMillis());// 返回相差月数long betweenMonth = DateUtil.betweenMonth(startDate, endDate, true);System.out.println(betweenMonth);System.out.println("------- day --------------");Date startDateDay = new Date(1553443200000L);Date endDateDay = new Date(System.currentTimeMillis());// 返回相差天数long betweenDay = DateUtil.betweenDay(startDateDay, endDateDay, true);System.out.println(betweenDay);System.out.println("------- MS --------------");Date startDateMs = new Date(1553443200000L);Date endDateMs = new Date(System.currentTimeMillis());// 返回相差毫秒数long betweenMs = DateUtil.betweenMs(startDateMs, endDateMs);System.out.println(betweenMs);
通过枚举传参形式实现,包括 week、day、hour、minute、second、ms
Date startDate = new Date(1553443200000L);Date endDate = new Date(System.currentTimeMillis());// DateUnit.DAY 枚举long between = DateUtil.between(startDate, endDate, DateUnit.DAY);System.out.println(between);
DateUnit 代码实现:
/** * 日期时间单位,每个单位都是以毫秒为基数 * @author Looly * */public enum DateUnit {/** 一毫秒 */MS(1), /** 一秒的毫秒数 */SECOND(1000), /**一分钟的毫秒数 */MINUTE(SECOND.getMillis() * 60),/**一小时的毫秒数 */HOUR(MINUTE.getMillis() * 60),/**一天的毫秒数 */DAY(HOUR.getMillis() * 24),/**一周的毫秒数 */WEEK(DAY.getMillis() * 7);private long millis;DateUnit(long millis){this.millis = millis;}/** * @return 单位对应的毫秒数 */public long getMillis(){return this.millis;}}
2 java8实现
String text1 = "2019-03-25";Temporal startDate = LocalDate.parse(text1);String text2 = "2022-05-30";Temporal endDate = LocalDate.parse(text2);System.out.println("------- year --------------");// 方法返回为相差年数long years = ChronoUnit.YEARS.between(startDate, endDate);System.out.println(years);System.out.println("------- month --------------");// 方法返回为相差月数long months = ChronoUnit.MONTHS.between(startDate, endDate);System.out.println(months);System.out.println("------- day --------------");// 方法返回为相差天数long days = ChronoUnit.DAYS.between(startDate, endDate);System.out.println(days);