Calendar是java的第二代日期类,而且是一个抽象类,并且构造器私有化,只能通过getInstance来获取实例
getInstance
获取Calendar实例
有四种重载形式
1 2 3
|
Calendar calendar = Calendar.getInstance();
|
getTime
将Calendar实例转换成Date对象
public final Date getTime()
1 2
| Calendar calendar = Calendar.getInstance(); Date date = calendar.getTime();
|
toInstant
将Calendar实例转换为Instant对象
public final Instant toInstant()
1 2
| Calendar calendar = Calendar.getInstance(); Instant instant = calendar.toInstant();
|
get
获取Calendar某个字段的值,返回月的时候,是从0开始的,所以输出的时候,需要+1
public int get(int field)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| Calendar calendar = Calendar.getInstance(); System.out.println("年:" + calendar.get(Calendar.YEAR)); System.out.println("月:" + (calendar.get(Calendar.MONTH) + 1)); System.out.println("日:" + calendar.get(Calendar.DAY_OF_MONTH)); System.out.println("一周的星期几:" + calendar.get(Calendar.WEEK_OF_MONTH)); System.out.println("一年的第几周:" + calendar.get(Calendar.WEEK_OF_YEAR)); System.out.println("时(十二小时制):" + calendar.get(Calendar.HOUR)); System.out.println("时(二十四小时制):" + calendar.get(Calendar.HOUR_OF_DAY)); System.out.println("分:" + calendar.get(Calendar.MINUTE)); System.out.println("秒:" + calendar.get(Calendar.SECOND));
|
格式化时间
Calendar类没有为我们提供格式化日期和时间的方法,需要我们自己手动格式化
1 2 3 4 5 6 7
| Calendar calendar = Calendar.getInstance(); System.out.println(calendar.get(Calendar.YEAR) + "-" + (calendar.get(Calendar.MONTH) + 1) + "-" + calendar.get(Calendar.DAY_OF_MONTH) + " " + calendar.get(Calendar.HOUR_OF_DAY) + ":" + calendar.get(Calendar.MINUTE) + ":" + calendar.get(Calendar.SECOND));
|
setTime
传入一个Date对象完成Calendar时间的设置
public final void setTime(Date date)
Calendar calendar = Calendar.getInstance();
calendar.setTime(new Date(993));