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()));
}
}
运行结果如下: