Java如何把字符串表示的日期按要求變爲多少天前,多少天后

需求

用Java把字符串表示的日期按要求自動變爲多少天前,多少天后?

代碼

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

public class Hello {
    // @author 孫琨
    public static void main(String[] args) {
        // TODO Auto-generated method stub
//      Date d = new Date();
//      SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
//      String dateNowStr = sdf.format(d);
//      System.out.println("格式化後的日期:" + dateNowStr);
//      boolean s1 = true;
//      boolean s2 = true;
//      boolean s = false;
//      s = s1 && s2;
//      System.out.println(s);

        String logDay = "20170501";
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        try {
            Date date = sdf.parse(logDay);
            Calendar calendar = new GregorianCalendar();
            calendar.setTime(date);
            calendar.add(calendar.DATE, -1); // 負數爲提前幾天,正數爲推遲幾天
            date = calendar.getTime();
            String greenDay = sdf.format(date);
            System.out.println(greenDay);
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

}
發佈了86 篇原創文章 · 獲贊 91 · 訪問量 48萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章