java date相关

时间:2022-03-17 17:00:26

public static void getPreDay() throws ParseException{
    String dateStr="2013-1-1";
    Date date=formatToDate(dateStr, "yyyy-MM-dd");
    System.out.println(dateStr);
   
    Calendar calendar = Calendar.getInstance();
    calendar.setTime(date);
    calendar.add(Calendar.DATE, -1);    //得到前一天
    //calendar.add(Calendar.MONTH, -1);    //得到前一个月

    System.out.println(formatToString(calendar.getTime(), "yyyy-MM-dd"));
}

public static Date formatToDate(String strDate,String format) throws ParseException{
    DateFormat df=new SimpleDateFormat(format);
    return df.parse(strDate);
}

public static String formatToString(Date date,String format){
    DateFormat df=new SimpleDateFormat(format);
    return df.format(date);
}