java中有关Date的计算问题

img


比如图中时间2021-11-11 12:20:08,我想得到2021-11-10 00:00:00这个时间,求问该怎么实现

Calendar 的 set() 方法了解一下

思路:研究下hutool 工具包;如果在java 中计算时间,你可以从数据库中取到这个时间,然后减去1天,小时的时间也可以偏移;DateUtil.offsetDay(当前时间, -1)

不知道你的意思是不是获取到指定时间的前一天00:00:00
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date curDate = sdf.parse("2021-11-11 12:20:08");
Calendar calendar = Calendar.getInstance();
calendar.setTime(curDate);
calendar.add(Calendar.DAY_OF_MONTH, -1);
Date date1 = calendar.getTime();
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd 00:00:00");
System.err.println(simpleDateFormat.format(date1));

 package cn.hutool.core.date;

String time="2021-11-11 12:20:08";
DateTime dateTime = DateUtil.offsetDay(DateUtil.parseDate(time), -1);
String yestDayTime = DateUtil.formatDateTime(dateTime);
System.out.println(yestDayTime);

通过时间差来计算。

public class Main {
    public static void main(String[] args) throws ParseException {
        String time="2021-11-11 12:20:08";
        SimpleDateFormat format=new SimpleDateFormat("YYYY-MM-dd");
        SimpleDateFormat format2=new SimpleDateFormat("YYYY-MM-dd HH:mm:ss");
        Date parse = format.parse(time.split(" ")[0]);
        System.out.println(format2.format(parse));
    }
}

img