java時間加減

Love丶蘭發表於2016-11-28

java時間加減

java時間相加減,感覺挺好用的,留下備份,需要的拿去

package com.controller;

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

public class WeatherController {
	
	public static void main(String[] args) throws ParseException {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
		Calendar date = Calendar.getInstance();
		date.setTime(sdf.parse("2016-11-05 09:00:00"));
		System.out.println("date.getTime():" + sdf.format(date.getTime()));
		date.set(Calendar.DATE, date.get(Calendar.DATE) -30);
		System.out.println("date.getTime():" + sdf.format(date.getTime()));
		date.add(Calendar.DATE, 23);		//下面的獲取的時間   就是  修改後的時間了
		System.out.println("date.getTime():" + sdf.format(date.getTime()));
		System.out.println("Calendar.MINUTE:" + Calendar.MINUTE);
		System.out.println("date.getTime():" + sdf.format(date.getTime()));
		System.out.println("年: " + date.get(Calendar.YEAR));  
        	System.out.println("月: " + (date.get(Calendar.MONTH) + 1) + "");  
       	 	System.out.println("日: " + date.get(Calendar.DAY_OF_MONTH));  
        	System.out.println("時: " + date.get(Calendar.HOUR_OF_DAY));
        	System.out.println("時: " + (date.get(Calendar.HOUR_OF_DAY) - 3));  
        	System.out.println("分: " + date.get(Calendar.MINUTE));  
        	System.out.println("秒: " + date.get(Calendar.SECOND));  
        	System.out.println("當前時間毫秒數:" + date.getTimeInMillis());  
        	System.out.println(date.getTime());  
        	System.out.println(date.get(Calendar.DATE)); 
        	System.out.println("---------------");

		date.add(Calendar.MINUTE, 30);// 30分鐘後的時間
		System.out.println(sdf.format(date.getTime()));
		date.add(Calendar.MINUTE, -120);// 30分鐘前的時間
		System.out.println(sdf.format(date.getTime()));
	}
}


相關文章