Java中的Calendar日历API用法完全解析
Calendar类是java.util包中的重要类,它提供了对日期和时间进行操作的各种方法。在Java中,常常使用Calendar类表示和操作日期和时间,而不是使用Date类。
Calendar类中常用的方法
- 获取日期和时间信息:get()
Calendar calendar = Calendar.getInstance();
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.MINUTE);
int second = calendar.get(Calendar.SECOND);
- 设置日期和时间信息:set()
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.YEAR, 2020);
calendar.set(Calendar.MONTH, Calendar.DECEMBER);
calendar.set(Calendar.DAY_OF_MONTH, 31);
calendar.set(Calendar.HOUR_OF_DAY, 23);
calendar.set(Calendar.MINUTE, 59);
calendar.set(Calendar.SECOND, 59);
- 日期和时间的加减操作:add()
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.YEAR, 1);
calendar.add(Calendar.MONTH, 3);
calendar.add(Calendar.DAY_OF_MONTH, 5);
calendar.add(Calendar.HOUR_OF_DAY, 2);
calendar.add(Calendar.MINUTE, 30);
calendar.add(Calendar.SECOND, 13);
示例一:输出当前日期和时间
Calendar calendar = Calendar.getInstance();
int year = calendar.get(Calendar.YEAR);
int month = calendar.get(Calendar.MONTH) + 1;
int day = calendar.get(Calendar.DAY_OF_MONTH);
int hour = calendar.get(Calendar.HOUR_OF_DAY);
int minute = calendar.get(Calendar.MINUTE);
int second = calendar.get(Calendar.SECOND);
System.out.println("当前日期:" + year + "-" + month + "-" + day);
System.out.println("当前时间:" + hour + ":" + minute + ":" + second);
运行结果:
当前日期:2022-9-30
当前时间:9:0:0
示例二:输出指定日期加上指定天数后的日期
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.YEAR, 2022);
calendar.set(Calendar.MONTH, Calendar.OCTOBER);
calendar.set(Calendar.DAY_OF_MONTH, 1);
int daysToAdd = 10;
calendar.add(Calendar.DAY_OF_MONTH, daysToAdd);
int year = calendar.get(Calendar.YEAR);
int month = calendar.get(Calendar.MONTH) + 1;
int day = calendar.get(Calendar.DAY_OF_MONTH);
System.out.println("指定日期加上" + daysToAdd + "天后的日期为:" + year + "-" + month + "-" + day);
运行结果:
指定日期加上10天后的日期为:2022-10-11
以上是Calendar日历API的简单用法示例,通过这些示例可以体会到Calendar类操作日期和时间的方便和灵活。
本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:Java中的Calendar日历API用法完全解析 - Python技术站