一、Date中常用的方法
- int getYear() (返回现在到1900年所经历的年份)
- int getMonth() (返回值是0-11)
- int getDate() (返回的是月份中的某一天,返回值在1-31之间)
- int getDay() (返回某周的第几天, 注: 周末为第一天, 返回值为0-6)
- int getHours() (返回第几个小时)
- int getMinutes() (返回多少分钟)
- int getSeconds() (返回秒数)
- long getTime() (获取日期对象从1970年的1月1日00:00:00到现在的时间毫秒数)
- void setTime(long time) (设置时间,time为设置的时间到1970年1月1日00:00:00的时间毫秒数)
- boolean after(Date when) (测试日期在指定日期之后则返回为true,否则为false)
- boolean before(Date when) (测试日期在指定日期之前则返回为true,否则为false)
二、Calendar
2.1、Calendar是一个接口,实例化接口有两种方法
1 : `Calendar calendar = new GregorianCalendar();`
2 : `Calendar calendar = Calendar.getInstance();`
2.2、Calendar中常用的方法
- calendar.getTimeInMills() (获取calendar到1970年的时间毫秒数)
- calendar.getTime() (将当前calendar转换成Date类型);
- calendar.get(Calendar.Year); (获取年份,与Date中获取年不同)
- calendar.get(Calendar.DAY_OF_WEEK)等等很多类似的方法
- calendar.set(Calendar.Year,2012);(将年份时间设置为2012年)等等也有很多类似的方法
- calendar.set(year,month,date)set方法也可以这样写
- calendar.add(Calendar.Year,-1); (倒退一年时间)
例如: 让你求没一年的2月的最后一天可以用三月第一天然后都退一天得到
三、Date,Calendar和String类型的联系与相互转换
3.1、String---->Date---->Calendar
String time = "20121023";
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd");
Date parse = simpleDateFormat.parse(time);
Calendar calendar = new GregorianCalendar();
calendar.setTime(parse);
3.2、Calendar---->Date---->String
Calendar calendar = Calendar.getInstance();
Date date = calendar.getTime();
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd");
String format = simpleDateFormat.format(date);
注:
1: SimpleDateFormat不能直接用于Calendar,它主要是用于String和Date类型的相互转换.
2: System.current.TimeMills() (从目前到1970年的时间毫秒数)
3: 年:yyyy, 月:MM, 日: dd, 时:HH, 分: mm, 秒: ss
4: 中国在东八区,所以会在时间上加上8个小时.