java日期時間基本操作方法

來源:文萃谷 2.85W

1. 獲得Calendar實例:Calendar c = nstance();

java日期時間基本操作方法

2. 定義日期/時間的格式:SimpleDateFormat sdf =new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

3. 把日期/時間轉換成固定格式,使用SimpleDateFormat的'format()方法:

String datetime = at(ime());

4. 把字符串轉換成日期/時間,使用SimpleDateFormat的parse()方法:Date d = e("2016-08-08 16:43:00");

5. 日期/時間的增加,減少,使用Calendar的add()方法,如將日期減少100天:(, -100);

6. 日期/時間的設置,使用Calendar的set()方法,如將小時設置為0時:

(_OF_DAY, 0);

例子:

package myCalendar;import eException;import leDateFormat;import ndar;import ;public class myCalendar { public static void main(String args[]) throws Exception{ Calendar c = nstance(); SimpleDateFormat sdf1 =new SimpleDateFormat("yyyyMMdd"); SimpleDateFormat sdf2 =new SimpleDateFormat("HHmmss"); SimpleDateFormat sdf3 =new SimpleDateFormat("yyyyMMddHHmmss"); SimpleDateFormat sdf4 =new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String date = at(ime()); tln(date); String time = at(ime()); tln(time); String dt = "20160808162405"; Date d = e(dt); dt = at(d); ime(d); (, -100); (_OF_DAY, 0); (TE, 0); (ND, 0); tln("100天前:" + at(ime())); (, 200); (_OF_DAY, 0); (TE, 0); (ND, 0); tln("100天后:" + at(ime())); }}

熱門標籤