1.Calender和Date相互转化
public static void main(String[] args) { // TODO Auto-generated method stub Calendar calendar = Calendar.getInstance(); // System.out.println(calendar.getTime()); // 实际上是调用Date date=new Date() calendar.setTime(new Date()); System.out.println(calendar.getTime()); }
2.Calendar的基本用法:
public static void main(String[] args) { // TODO Auto-generated method stub Calendar calendar = Calendar.getInstance(); //获取calendar实例 System.out.println(calendar.get(Calendar.YEAR)); //分别输出calendar中的年月日 System.out.println(calendar.get(Calendar.MONTH)); System.out.println(calendar.get(Calendar.DATE)); calendar.set(2011, 1, 3); //设置calendar的时间 System.out.println(calendar.getTime()); //输出设置后的时间 calendar.add(calendar.MONTH, 13); //用add加,超过的单位会进一 System.out.println(calendar.getTime()); calendar.roll(calendar.MONTH, 13); //roll加,超过的单位不会进一 System.out.println(calendar.getTime()); } result: 2013 11 15 Thu Feb 03 00:15:22 CST 2011 Sat Mar 03 00:15:22 CST 2012 Tue Apr 03 00:15:22 CST 2012
3.Calendar的容错性
public static void main(String[] args) { // TODO Auto-generated method stub Calendar calendar = Calendar.getInstance(); //获取calendar实例 calendar.set(calendar.MONTH,12); //超过的部分在上一级加一(11+12)在year++ System.out.println(calendar.getTime()); //正常 calendar.setLenient(false); //关闭容错性,11+12在month的范围之外,判断错误 calendar.set(calendar.MONTH , 12); System.out.println(calendar.getTime()); //错误 }
4.set方法的延迟修改
public static void main(String[] args) { // TODO Auto-generated method stub Calendar calendar = Calendar.getInstance(); //获取calendar实例 calendar.set(2013, 7, 31); //month计数从0开始,所以是2013-08-31 System.out.println(calendar.getTime()); calendar.set(calendar.MONTH, 8); //设置为9月:2013-9-? set延迟效应,具体时间还没确定,出现get时才确认 // System.out.println(calendar.getTime()); //这时get,那么为2013-10-01 因为没有2013-09-31 calendar.set(calendar.DATE, 5); //如果上述get没有,这里就是设置date 为5 System.out.println(calendar.getTime()); //这时两个set起作用 2013-09-05 }