1. 程式人生 > 其它 >mybatisplus時間範圍查詢

mybatisplus時間範圍查詢

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);