將時間根據傳入的參數進行加減(以秒爲單位爲單位)

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

public class DateUtil {


    /**
     * 將當前時間減去time秒
     * @param time
     * @return
     */
    public  static  String getDateTo(Date date,int time){
            try {
                SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                Calendar c = new GregorianCalendar();
                //Date date = new Date();
                System.out.println("系統當前時間      :"+df.format(date));
                c.setTime(date);//設置參數時間
                c.add(Calendar.SECOND,-time);//把日期往後增加SECOND 秒.整數往後推,負數往前移動
                date=c.getTime(); //這個時間就是日期往後推一天的結果
                String str = df.format(date);
                System.out.println("系統前"+time+"秒時間:"+str);
                return str;
            }catch (Exception e){
                e.printStackTrace();
                return null;
            }
        }


    public static void main(String[] args) {
        getDateTo(new Date(),60);
    }
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章