在开发中,如果我们想查询数据库中某一天所有某个或所有时间点的数据,那么就要先获得当天的所有想查询的时间点
本人开发中的真实案例: 需要把当天从00:00开始到第二天的00:00(半小时(30分钟)为间隔)的数据全部查询出来展示**
相当于就是00:00,00:30,01:00,01:30,02:00,02:30…
获得我们想要的所有时间点之后,可使用sql模糊或精确查询数据库日期时间字段
小伙伴们很好奇为什么要以30分钟为间隔,解释下哈:本人项目中的数据库日期时间字段都是间隔30分钟的哈,意思是要么是整点比如12:00,要么就是:12:30所有不存在其他时间哈
package com.date.test;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
/**
* @author: libo
* @date: 2020/9/22 18:02
* @motto: 即使再小的帆也能远航
*/
@SpringBootTest
public class test {
@Test
public void test() throws ParseException {
/*获取当天日期*/
Date date = new Date();
/*设置日期格式*/
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
/*将日期转为字符串*/
String today = df.format(date);
/*将字符串转为Date类型*/
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
/*从当前日期的00:00开始*/
Date parse = simpleDateFormat.parse(today + " 00:00");
/*输出开始日期时间*/
String format = simpleDateFormat.format(parse);
System.out.println(format);
/*循环47次(24*2-1获得每半个小时的时间 第一天00:00到第二天00:00)*/
for (int y = 0; y < 48; y++) {
/*将指定时间依次加30分钟,循环到23:30为止(以此类推,如果是获取按小时划分, +60分钟)*/
Calendar c = Calendar.getInstance();
/*设置指定时间*/
c.setTime(parse);
/*将设置的时间加上30分钟*/
c.add(Calendar.MINUTE, 30);
/*获得加上30分钟后的时间*/
Date dateTime = c.getTime();
/*将新时间赋值后再循环*/
parse = dateTime;
/*将date转为字符串*/
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
String format2 = sdf.format(dateTime);
System.out.println(format2);
}
}
}