Java中的時間計算 Calendar類的加減

2021-07-31 11:55:02 字數 1821 閱讀 7454

啥也不說了直接上**

/*-------------------------時間計算start---------------------------------*/

//hh表示24小時制 hh表示12小時制

******dateformat dft = new ******dateformat("yyyy-mm-dd hh:mm:ss");

date mydate = dft.parse("2017-04-29 00:00:00");//需要計算的時間

calendar date = calendar.getinstance();//獲取calendar例項

date.settime(mydate);

date.set(calendar.date, date.get(calendar.date) + 1);//天+1

date.set(calendar.month, date.get(calendar.month) + 1);//月+1

date.set(calendar.year, date.get(calendar.year) + 1);//年+1

// date.set(calendar.hour, date.get(calendar.hour) + 1);//小時+1

//分鐘+1(12小時制) 由於我上面用的是hh 所有輸出還是24小時制

date.set(calendar.minute, date.get(calendar.minute) + 1);

date.set(calendar.second, date.get(calendar.second) + 1);//秒+1

//分鐘+1 (24小時制)

date.set(calendar.hour_of_day, date.get(calendar.hour_of_day) + 1);

date enddate = dft.parse(dft.format(date.gettime()));

system.out.println("我的時間mydate:"+"\n"+dft.format(mydate));

system.out.println("計算後我的時間enddate:"+"\n"+dft.format(enddate));

/*-------------------------時間計算end---------------------------------*/

/*----------------------接下來系統當前時間的獲取start-------------------*/

date begindate = new date();//系統當前時間

system.out.println("系統當前時間new date()方式:"+"\n"+dft.format(begindate));

long nowtime=system.currenttimemillis();//系統當前時間 返回毫秒

system.out.println("系統當前時間system.currenttimemillis()方式:"+"\n"+dft.format(nowtime));

/*---------------------接下來系統當前時間的獲取end-----------------*/

執行結果:

其實這兩種獲取當前系統時間的方式是一樣的。

看看date的構造就明白了- -

java 計算程式執行的時間

求第100002個素數 2013 07 05 08 26 08 收藏 12 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 packagejian...

java計算時間差

1 假設乙個時間是string date1 2012 8 12 2 當前的時間是 date datenow new date dateformat sdf new dateformat yyyy mm dd string date2 sdf.format datenow 4 date date11 ...

Java計算時間戳差值

計算time2減去time1的差值 差值只設定 幾天 幾個小時 或 幾分鐘 根據差值返回多長之間前或多長時間後 public static string getdistancetime long time1,long time2 else day diff 24 60 60 1000 hour di...