Calendar类
- Calendar提供了获取或设置各种日历字段的方法。
1. 构造方法
protected Calendar()
由于修饰符是protected,所以无法直接创建对象
2. 其他方法
方法名 |
说明 |
static Calendar getInstance() |
使用默认时区和区域获取日历 |
void set(int year, int month, int date, int hourOfDay, int minute, int secend) |
设置日历的年、月、日、时、分、秒 |
int get(int field) |
法牛给定日历字段的值。字段比如年、月、日等 |
void setTime(Date date) |
用给定的Date设置此日历的时间。Date-Calendar |
Date getTime() |
返回一个Date表示此日历的时间。Calendar-Date |
void add(int field, int amount) |
按照日历的规则,给指定字段添加或减少时间量 |
long getTimeInMillies() |
毫秒为单位返回该日历的时间值 |
int getActualMaximum(int field) |
获取指定字段可能的最大值,比如判断2月有多少天 |
int getActualMinimum(int field) |
获取指定字段可能的最小值,比如判断2月有多少天 |
3. 使用
Calendar calendar = Calendar.getInstance();
System.out.println(calendar.getTime());
System.out.println(calendar.getTime().toLocaleString());
System.out.println(calendar.getTimeInMillis());
int year = calendar.get(Calendar.YEAR);
int month = calendar.get(Calendar.MONTH);
int day = calendar.get(Calendar.DAY_OF_MONTH);
int hour = calendar.get(Calendar.HOUR_OF_DAY);
int minute =calendar.get(Calendar.SECOND);
Calendar calendar2 = Calendar.getInstance();
System.out.println(calendar2.getTime().toLocaleString());
calendar2.set(Calendar.DAY_OF_MONTH, 5);
System.out.println(calendar2.getTime().toLocaleString());
Calendar calendar3 = Calendar.getInstance();
System.out.println(calendar3.getTime().toLocaleString());
calendar3.add(Calendar.YEAR, -1);
System.out.println(calendar3.getTime().toLocaleString());
Calendar calendar = Calendar.getInstance();
System.out.println(calendar.getTime().toLocaleString());
calendar.set(Calendar.MONTH, Calendar.FEBRUARY);
System.out.println(calendar.getActualMaximum(Calendar.DAY_OF_MONTH));
System.out.println(calendar.getActualMinimum(Calendar.DAY_OF_MONTH));