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、测试结果

 

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM