Java 获取昨天、前天时间
1、代码
public class DateUtils {
    public static void main(String[] args) throws ParseException {
        String str = "2021-11-01 06:07:08";
        Date date = str2Date(str);
        System.out.println("当天时间为: " + str);
        System.out.println("昨天时间为: " + getYesterday(date));
        System.out.println("前天时间为: " + getBeforeYesterday(date));
    }
    // 字符串转日期
    public static Date str2Date(String str) throws ParseException {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = sdf.parse(str);
        return date;
    }
    // 获取昨天的时间格式字符串
    public static String getYesterday(Date date) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Calendar calendar = new GregorianCalendar();
        calendar.setTime(date);
        calendar.add(calendar.DATE, -1);
        return sdf.format(calendar.getTime());
    }
    // 获取前天的时间格式字符串
    public static String getBeforeYesterday(Date date) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Calendar calendar = new GregorianCalendar();
        calendar.setTime(date);
        calendar.add(calendar.DATE, -2);
        return sdf.format(calendar.getTime());
    }
}
2、测试结果

                    
                
                
            
        
浙公网安备 33010602011771号