java获取指定日期的前一天和上月最后一天(自用笔记)

package com.tsu.time;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public class getYesterday {
    public static void main(String[] args) {
        System.out.println(getYesterday("20200731"));//20200730
        System.out.println(getLastMonth("20200731"));
    }

    //获取指定日期的前一天
    public static String getYesterday(String bizdate){

        Date date = new Date();
        Date yesterday = new Date();

        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        try {
            date = sdf.parse(bizdate);
            Calendar cal = Calendar.getInstance();
            cal.setTime(date);
            cal.add(Calendar.DAY_OF_MONTH,-1);
            yesterday = cal.getTime();
            return sdf.format(yesterday);
            //System.out.println(sdf.format(yesterday));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return sdf.format(date);

    }
    //获取指定日期的上个月最后一天
    public static String getLastMonth(String bizdate){
        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        try {
            date = sdf.parse(bizdate);
            Calendar cal = Calendar.getInstance();
            cal.setTime(date);
            cal.add(Calendar.MONTH,-1);
            cal.set(Calendar.DAY_OF_MONTH,cal.getActualMaximum(Calendar.DAY_OF_MONTH));
            date = cal.getTime();
            return sdf.format(date);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return sdf.format(date);
    }
}

输出结果

java获取指定日期的前一天和上月最后一天(自用笔记)_第1张图片

你可能感兴趣的:(日期常用方法)