java date相關

滄海一滴發表於2013-06-22

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);
}

相關文章