mybatisplus时间范围查询

mybatisplus,时间范围查询的两种方式。下面以查询当天的数据为例。(备注:?表示具体的实体类)

一、between()

 LambdaQueryWrapper<?> lq = Wrappers.lambdaQuery();
        Date start = DateUtil.strToDateLong(DateUtil.dateToStr(new Date(), Locale.CHINA) + " 00:00:00");
        Date end = DateUtil.strToDateLong(DateUtil.dateToStr(new Date(), Locale.CHINA) + " 23:59:59");
        lq.between(?::getCreateTime, start, end);

引用的时间类:

import java.text.DateFormat;
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;

public class DateUtil {

    public static ThreadLocal<DateFormat> chinaDateSDF = new ThreadLocal<DateFormat>() {

        @Override
        protected DateFormat initialValue() {
            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd", Locale.CHINA);
            return df;

        }
    };

    /**
     * 获取日期yyyy-MM-dd格式字符串
     *
     * @param date
     * @param locale
     * @return
     */
    public static String dateToStr(Date date, Locale locale) {
        if (locale == null) {

        }
        return chinaDateSDF.get().format(date);
    }

    /**
     * 将长时间格式字符串转换为时间 yyyy-MM-dd HH:mm:ss
     *
     * @param strDate
     * @return
     */
    public static Date strToDateLong(String strDate) {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        ParsePosition pos = new ParsePosition(0);
        Date strtodate = formatter.parse(strDate, pos);
        return strtodate;
    }
}

 

二、结合ge()和le()

 LambdaQueryWrapper<?> lambdaQueryWrapper = Wrappers.lambdaQuery();
        Calendar start = Calendar.getInstance();
        Calendar end = Calendar.getInstance();
        start.add(Calendar.DATE,-1);
        //
        start.set(Calendar.HOUR_OF_DAY, 0);
        //
        start.set(Calendar.MINUTE, 0);
        //
        start.set(Calendar.SECOND, 0);

        String startDate = simpleDateFormat.format(start.getTime());

        //
        end.set(Calendar.HOUR_OF_DAY, 0);
        //
        end.set(Calendar.MINUTE, 0);
        //
        end.set(Calendar.SECOND, 0);

        String endDate = simpleDateFormat.format(end.getTime());
        lambdaQueryWrapper.ge(?::getCreateTime,startDate).le(?::getCreateTime,endDate);

 

posted @ 2021-08-13 17:42  阿罗luo  阅读(25155)  评论(0编辑  收藏  举报