java中获取一天的开始时间和结束时间
先得导入hutool的核心包依赖, 因为获取开始和结束时间用的hutool中的DateUtil工具类。
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-core</artifactId>
<version>5.7.6</version>
</dependency>
获取当天的开始时间
DateTime beginOfDay = DateUtil.beginOfDay(new Date());
获取当天的结束时间
DateTime endOfDay = DateUtil.endOfDay(new Date());
在这里获取昨天的开始和结束时间需要结合Calendar和hutool一起使用
SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); //例如今天是 2021-07-29 16:55:45 //获取昨天开始的时间 Date beginOfDay = DateUtil.beginOfDay(new Date()); Calendar c = Calendar.getInstance(); c.setTime(beginOfDay); c.add(Calendar.DAY_OF_MONTH,-1); Date yesterBeginDay = c.getTime(); String a = simpleDateFormat.format(yesterBeginDay); System.out.println(a); 输出结果:2021-07-28 00:00:00 //获取昨天结束的时间 Date endOfDay = DateUtil.endOfDay(new Date()); c.setTime(endOfDay); c.add(Calendar.DAY_OF_MONTH,-1); Date yesterEndDay = c.getTime(); String b = simpleDateFormat.format(yesterEndDay); System.out.println(b); 输出结果:2021-07-28 23:59:59
参考:https://blog.csdn.net/Q36_524/article/details/119253774

浙公网安备 33010602011771号