Java判断时间是否在当天24h范围内,学习笔记

    写项目的时候,遇到一个需求,需要判断查询出来的数据更新时间是否为当天24h之内的数据,当然可以使用SQL语句 between 更新时间范围来查询;但是,有些特殊情况需要通过id先把所有满足id条件的数据查询出来,然后通过Java业务逻辑来处理满足当天时间范围内的数据给分页处理,这样就涉及到了一个判断是否为当天时间的工具类。

博主地址

package com.sjbb.utils;
 
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
 
import lombok.extern.slf4j.Slf4j;
 
/**
 * @Description 时间段判断
 * @author 刘鹏博
 * @version v1.0
 * @date 2018731
 */
@Slf4j
public class DateUtils {
    
    
	/**
	 * @Description 是否为当天24h内
	 * @author 刘鹏博
	 * @param inputJudgeDate 要判断是否在当天24h内的时间
	 * @return
	 * boolean
	 */
	public static boolean isToday(Date inputJudgeDate) {
    
    
		boolean flag = false;
		//获取当前系统时间
		long longDate = System.currentTimeMillis();
		Date nowDate = new Date(longDate);
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String format = dateFormat.format(nowDate);
		String subDate = format.substring(0, 10);
		//定义每天的24h时间范围
		String beginTime = subDate + " 00:00:00";
		String endTime = subDate + " 23:59:59";
		Date paseBeginTime = null;
		Date paseEndTime = null;
		try {
    
    
			paseBeginTime = dateFormat.parse(beginTime);
			paseEndTime = dateFormat.parse(endTime);
			
		} catch (ParseException e) {
    
    
			log.error(e.getMessage());
		}
		if(inputJudgeDate.after(paseBeginTime) && inputJudgeDate.before(paseEndTime)) {
    
    
			flag = true;
		}
		return flag;
	}
}

测试代码:

package com.sjbb.utils;
 
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
 
/**
 * @Description 判断当天时间工具测试
 * @author 刘鹏博
 * @version v1.0
 * @date 201881
 */
public class DateUtilsTest {
    
    
	public static void main(String[] args) {
    
    
		//测试时间1
		String testTimeOne = "2018-07-31 10:25:11";
		//测试时间2
		String testTimeTwo = "2018-08-01 13:09:51";
		//时间格式化
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Date psTestTimeOne = null;
		Date psTestTimeTwo = null;
		try {
    
    
			psTestTimeOne = format.parse(testTimeOne);
			psTestTimeTwo = format.parse(testTimeTwo);
		} catch (ParseException e) {
    
    
			e.printStackTrace();
		}
		boolean timeOneIsToday = DateUtils.isToday(psTestTimeOne);
		boolean timeTwoIsToday = DateUtils.isToday(psTestTimeTwo);
		System.out.println("测试时间输出为true,则处于当天24h范围内,false反之。");
		System.out.println("测试时间一:"+timeOneIsToday);
		System.out.println("测试时间二:"+timeTwoIsToday);
	}
}

猜你喜欢

转载自blog.csdn.net/sqL520lT/article/details/111933352