Calendar calendar = new GregorianCalendar();// 0可以修改,0代表当前时间,-1代表前一天calendar.add(Calendar.DAY_OF_MONTH,0);//一天的开始时间 yyyy:MM:dd 00:00:00calendar.set(Calendar.HOUR_OF_DAY,0);calendar.set(Calendar.MINUTE,0);calendar.set(Calendar.SECOND,0);calendar.set(Calendar.MILLISECOND,0);Date dayStart = calendar.getTime();SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");String startStr = simpleDateFormat.format(dayStart);//一天的结束时间 yyyy:MM:dd 23:59:59calendar.set(Calendar.HOUR_OF_DAY,23);calendar.set(Calendar.MINUTE,59);calendar.set(Calendar.SECOND,59);calendar.set(Calendar.MILLISECOND,999);Date dayEnd = calendar.getTime();
上面的是在java8之前的写法,当然在java8以后,有了localdatetime之后,写法也简单很多:
//获取当前时间LocalDateTime nowTime = LocalDateTime.now();//获取当前日期LocalDate nowDate = LocalDate.now();//设置零点LocalDateTime beginTime = LocalDateTime.of(nowDate, LocalTime.MIN);//将时间进行格式化Date start1 = Date.from(beginTime.atZone(ZoneId.systemDefault()).toInstant());//设置当天的结束时间LocalDateTime endTime = LocalDateTime.of(nowDate,LocalTime.MAX);//将时间进行格式化Date end1 = Date.from(endTime.atZone(ZoneId.systemDefault()).toInstant());