1. 獲得Calendar實例:
Calendar c = Calendar.getInstance();
2. 定義日期/時間的格式:
SimpleDateFormat sdf =new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
3. 把日期/時間轉換成固定格式,使用SimpleDateFormat的format()方法:
String datetime = sdf.format(c.getTime());
4. 把字符串轉換成日期/時間,使用SimpleDateFormat的parse()方法:
Date d = sdf3.parse("2016-08-08 16:43:00");
5. 日期/時間的增加,減少,使用Calendar的add()方法,如將日期減少100天:
c.add(Calendar.DATE, -100);
6. 日期/時間的設置,使用Calendar的set()方法,如將小時設置為0時:
c.set(Calendar.HOUR_OF_DAY, 0);
例子:
package myCalendar; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; public class myCalendar { public static void main(String args[]) throws Exception{ Calendar c = Calendar.getInstance(); 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 = sdf1.format(c.getTime()); System.out.println(date); String time = sdf2.format(c.getTime()); System.out.println(time); String dt = "20160808162405"; Date d = sdf3.parse(dt); dt = sdf4.format(d); c.setTime(d); c.add(Calendar.DATE, -100); c.set(Calendar.HOUR_OF_DAY, 0); c.set(Calendar.MINUTE, 0); c.set(Calendar.SECOND, 0); System.out.println("100天前:" + sdf4.format(c.getTime())); c.add(Calendar.DATE, 200); c.set(Calendar.HOUR_OF_DAY, 0); c.set(Calendar.MINUTE, 0); c.set(Calendar.SECOND, 0); System.out.println("100天後:" + sdf4.format(c.getTime())); } }
運行結果如下: