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

本文介绍了如何使用Java8的LocalDate结合Mybatis进行最近几个月的数据查询,通过简洁的SQL语句实现高效操作。并提及了List的反序方法Collections.reverse()。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

今天又得到了大佬的关爱,大佬教我用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);

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值