1.计算过去指定天数的时间:
/*** 计算过去天数,* 返回:日期 yyyy-MM-dd 00:00:00 String* */private String computDay(String day){//0:今天 7:过去七天 30:过去30天 90:过去三个月 180:过去半年 365:过去一年//month0:本月 month1:上一个月 month2:上两个月 month3:上三个月LocalDateTime now = LocalDateTime.now();String fomater="yyyy-MM-dd HH:mm:ss";String nowday = now.format(DateTimeFormatter.ofPattern(fomater));String strtime = nowday;switch (day){case "month0":strtime = now.minusMonths(0).format(DateTimeFormatter.ofPattern(fomater));break;case "month1":strtime = now.minusMonths(1).format(DateTimeFormatter.ofPattern(fomater));break;case "month2":strtime = now.minusMonths(2).format(DateTimeFormatter.ofPattern(fomater));break;case "month3":strtime = now.minusMonths(3).format(DateTimeFormatter.ofPattern(fomater));break;case "0":strtime = nowday;break;case "1":strtime = now.minusDays(1).format(DateTimeFormatter.ofPattern(fomater));break;case "7":strtime = now.minusDays(7).format(DateTimeFormatter.ofPattern(fomater));break;case "30":strtime = now.minusDays(30).format(DateTimeFormatter.ofPattern(fomater));break;case "90":strtime = now.minusDays(90).format(DateTimeFormatter.ofPattern(fomater));break;case "180":strtime = now.minusDays(180).format(DateTimeFormatter.ofPattern(fomater));break;case "365":strtime = now.minusDays(365).format(DateTimeFormatter.ofPattern(fomater));break;}return strtime;}
2.计算两个日期之间包含的所有日期。例如计算2020-10-12到2020-10-24之间的所有日期
/*** 计算两个日期之间的日期,包括两个开始和结束两个日期* */public List getDayListOnTwoDay(String start, String end){LocalDateTime parse = LocalDateTime.parse(start, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));LocalDateTime parse1 = LocalDateTime.parse(end, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));List list = new ArrayList();list.add(parse.format(DateTimeFormatter.ofPattern("yyyy-MM-dd")));LocalDateTime nextDay = parse.plusDays(1);//下一天在开始时间之后,在结束时间之前System.out.println(nextDay+"--"+nextDay.isAfter(parse) +","+ nextDay.isBefore(parse1));while (nextDay.isAfter(parse) && nextDay.isBefore(parse1)){list.add(nextDay.format(DateTimeFormatter.ofPattern("yyyy-MM-dd")));nextDay = nextDay.plusDays(1);}list.add(parse1.format(DateTimeFormatter.ofPattern("yyyy-MM-dd")));return list;}
3.计算指定日期之前天数的日期 。例如计算2020-10-12日前第2天的日期
/**** 计算某日期之前指定天数的日期* 参数:* 计算的日期* 计算天数* */public String getBeforTime(String startTime,Integer day){LocalDateTime time = LocalDateTime.parse(startTime,DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));return time.minusDays(day).format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));}
4.计算某日期之后指定天数的日期,例如计算2020-10-12日后第2天的日期
/**** 计算某日期之后指定天数的日期* 参数:* 计算的日期* 计算天数* */public String getAfterTime(String startTime,Integer day){LocalDateTime time = LocalDateTime.parse(startTime, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));return time.plusDays(day).format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));}