用java8的LocalDate实现最近几个月查询

今天又得到了大佬的关爱,大佬教我用LocalDate

       long num = 6l; //最近几个月
        
        // 月份
        LocalDate end = LocalDate.now().minusMonths(1);
        // 起始时间
        LocalDate start =  end.minusMonths(num);
        LocalDate firstday = LocalDate.of(start.getYear(), start.getMonthValue(), 1);
        //本月的最后一天
        LocalDate lastTheMonthDay = LocalDate.now().with(TemporalAdjusters.lastDayOfMonth());
        //上月的最后一天
        LocalDate lastMonthDay = end.with(TemporalAdjusters.lastDayOfMonth());
        
        System.out.println(end);
        System.out.println(start);
        System.out.println(firstday);
        System.out.println(lastTheMonthDay);
        System.out.println(lastMonthDay);

 

 

然后查询的时候 mybatis sql语句就写

       <if test="start !=null">
		<![CDATA[and take_time > #{start}]]>
			</if>
			<if test="end !=null">
		<![CDATA[and take_time <= #{end}]]>
			</if>

就搞定。真好用!真香!

补充:

 

 

 

final SimpleDateFormat ymdSimpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
		
		// 获取查询起始时间
				DateTimeFormatter yyyyMM = DateTimeFormatter.ofPattern("yyyy-MM");
				DateTimeFormatter yyyyMMdd = DateTimeFormatter.ofPattern("yyyy-MM-dd");
		long num = 12; // 几个月区间
		List<String> yearMonth = new ArrayList<>();
		List<String> yearMonthDay = new ArrayList<>();
		List<Date> yearMonthDayDates = new ArrayList<>();
		LocalDateTime now = LocalDateTime.now();
		for (int i = 0; i < num; i++) {
			now = now.minusMonths(1);
			yearMonth.add(yyyyMM.format(now));
			String yyyyMMddStr = yyyyMMdd.format(now);
			yearMonthDay.add(yyyyMMddStr);
			yearMonthDayDates.add(ymdSimpleDateFormat.parse(yyyyMMddStr));
		}
		LocalDateTime start = LocalDateTime.of(now.getYear(), now.getMonthValue(), 1, 0, 0);
		// 结束时间
		LocalDateTime end = LocalDateTime.now().minusMonths(1);
		LocalDateTime lastMonthDay = end.with(TemporalAdjusters.lastDayOfMonth());
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
		for (Date date : yearMonthDayDates) {
			System.out.println(format.format(date));
		}

List反序:Collections.reverse(list);

展开阅读全文

没有更多推荐了,返回首页