Calendar类,是一个抽象类,在java.util包中,实现了Serializable,Cloneable,和Comparable<Calendar>三个接口,功能是为了实现日期的设置与显示。在JDK1.1后,Calendar逐渐取代Date类,Date类中的大部分方法(包括构造方法)被声明为已过时Deprecated,不推荐使用。
1、如何得到Calendar类:
static Calendar | getInstance()
Gets a calendar using the default time zone and locale.
|
2、Calendar的几个重要函数:获取时间get(),设置时间set(),增加减少add()
get函数,根据指定字段获取年份,月数,日期,小时等
int | get(int field)
Returns the value of the given calendar field.
|
void | set(int field, int value)
Sets the given calendar field to the given value.
|
void | set(int year, int month, int date)
Sets the values for the calendar fields YEAR , MONTH , and DAY_OF_MONTH .
|
void | set(int year, int month, int date, int hourOfDay, int minute)
Sets the values for the calendar fields YEAR , MONTH , DAY_OF_MONTH , HOUR_OF_DAY , and MINUTE .
|
void | set(int year, int month, int date, int hourOfDay, int minute, int second)
Sets the values for the fields YEAR , MONTH , DAY_OF_MONTH , HOUR_OF_DAY , MINUTE , and SECOND .
|
abstract void | add(int field, int amount)
Adds or subtracts the specified amount of time to the given calendar field, based on the calendar's rules.
|
转换为Date类:相应的还有setTime方法
Date | getTime()
Returns a Date object representing this Calendar 's time value (millisecond offset from the Epoch").
|
long | getTimeInMillis()
Returns this Calendar's time value in milliseconds.
|
public static void main(String[] args){
Calendar cl=Calendar.getInstance();
//输出当前默认时间
int year = cl.get(Calendar.YEAR);
int month = cl.get(Calendar.MONTH)+1;//因月份是从0算起
int date = cl.get(Calendar.DATE);
int hour = cl.get(Calendar.HOUR_OF_DAY);//Hour是12小时格式
int minute = cl.get(Calendar.MINUTE);
int second = cl.get(Calendar.SECOND);
int week = cl.get(Calendar.DAY_OF_WEEK)-1;//默认星期天为第一天
System.out.println(year+" "+month+" "+date+" "+hour+" "+minute+" "+second+" "+week);
//装换为Date类输出
System.out.println(cl.getTime());
//转换为毫秒输出
System.out.println(cl.getTimeInMillis());
}
输出结果:
2015 10 30 17 50 19 5
Fri Oct 30 17:50:19 CST 2015
1446198619677
4、关于在设置字段值时注意
有setLenient(Boolean b)方法,lenient有宽容之意,就是对于月份、小时、日期、秒数等做一个限制
默认为true,如果显示设置为false,则一定要设置日期,秒数等在合理范围内,否则抛出异常