日期类Calendar和Date的用法总结

1.Calendar与Date互转:
(1) Calendar转化为Date

Calendar cal=Calendar.getInstance();
Date date=cal.getTime();


(2) Date转化为Calendar

Date date=new Date();
Calendar cal=Calendar.getInstance();
cal.setTime(date);

2.Calendar获取年、月、日、分钟等的方法:
Calendar c = Calendar.getInstance(TimeZone.getTimeZone("GMT+08:00"));//获取东八区时间

  int year = c.get(Calendar.YEAR);    //获取年
  int month = c.get(Calendar.MONTH) + 1;   //获取月份,0表示1月份
  int day = c.get(Calendar.DAY_OF_MONTH);    //获取当前天数
  int first = c.getActualMinimum(c.DAY_OF_MONTH);    //获取本月最小天数
  int last = c.getActualMaximum(c.DAY_OF_MONTH);    //获取本月最大天数
  int time = c.get(Calendar.HOUR_OF_DAY);       //获取当前小时
  int min = c.get(Calendar.MINUTE);          //获取当前分钟
  int xx = c.get(Calendar.SECOND);          //获取当前秒

3.Date类比较大小
  Date endDate = DateParameterUtil.getEndTimeParam(request, true, 0) ;
  SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
  String logTimeNodeStr = "2014-12-01 00:00:00";
  Date logTimeNodeDate = dateFormat.parse(logTimeNodeStr);
  if(endDate.compareTo(logTimeNodeDate)==-1){
    System.out.println("endDate 早于2014-12-01 00:00:00");
  }
  if(endDate.compareTo(logTimeNodeDate)==0){
    System.out.println("endDate 等于2014-12-01 00:00:00");
  }
  if(endDate.compareTo(logTimeNodeDate)==1){
    System.out.println("endDate 大于2014-12-01 00:00:00");
  }
  另还有方法:
  java.util.Date.before(java.util.Date anotherDate); //是否早于anotherDate
  java.util.Date.after(java.util.Date anotherDate);  //是否晚于anotherDate

4.Calendar类比大小
   boolean java.util.Calendar.before(Object when); //是否早于when
   boolean java.util.Calendar.after(Object when);  //是否晚于when
   int java.util.Calendar.compareTo(Calendar anotherCalendar); //早,返回-1;相同,返回0;晚,返回1

你可能感兴趣的:(calendar)