Java Calendar详解 - 创建、获取、转换、日期加减

2014-07-22· 7752 次浏览
## 创建 Java月份是从0-11,月份设置时要减1 ```java // 使用当前时间创建 Calendar calendar = Calendar.getInstance(); // 设置指定日期,月份需要减一 calendar.set(year, month - 1, day); // 指定时间创建,参数依次为:年,月,日,时,分,秒,月份需要减一 Calendar calendar = new GregorianCalendar(2016, 8, 1, 15, 41, 22); // Date转换为Calendar Calendar calendar = Calendar.getInstance(); calendar.setTime(date); ``` ## 获取 ### 获取年、月、日、时、分、秒、星期 ```java Calendar calendar = Calendar.getInstance(); int year = calendar.get(Calendar.YEAR); // 取月份要加1 int month = calendar.get(Calendar.MONTH) + 1; int day = calendar.get(Calendar.DAY_OF_MONTH); int hover = calendar.get(Calendar.HOUR_OF_DAY); int minute = calendar.get(Calendar.MINUTE); int seconds = calendar.get(Calendar.SECOND); // 1-7分别代表 -- 星期日,星期一,星期二,星期三,星期四,星期五,星期六 int week = calendar.get(calendar.DAY_OF_WEEK); ``` ### 获取当前月份的最大天数 ```java Calendar.getInstance().getActualMaximum(Calendar.DAY_OF_MONTH); ``` ## 操作 ### Calendar 转换为Date ```java Date date = Calendar.getInstance().getTime(); ``` ### 日期加减 ```java public class TestCalendar { // 使用默认时区和语言环境获得一个日历。 private static Calendar calendar = Calendar.getInstance(); public static void print(String name) { System.out.print(name + ": "); System.out.println(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(calendar.getTime())); } public static void main(String[] args) { print("当前时间 "); calendar.add(Calendar.HOUR_OF_DAY, 1); print("增加1小时"); calendar.add(Calendar.DAY_OF_MONTH, 1); print("增加1天 "); calendar.add(Calendar.MONTH, 1); print("增加1个月"); calendar.add(Calendar.YEAR, 1); print("增加1年 "); calendar.add(Calendar.YEAR, -2); print("减少2年 "); } } ``` ### 两个日期相差天数 ```java long millisOfDay = 24 * 60 * 60 * 1000; Calendar calendar = new GregorianCalendar(2015, 9, 1); Calendar calendar1 = new GregorianCalendar(2016, 9, 1); Calendar calendar2 = new GregorianCalendar(2017, 9, 1); // 2016年是闰年,得到366天 System.out.println((calendar1.getTimeInMillis() - calendar.getTimeInMillis()) / millisOfDay); // 2017年是平年,得到365天 System.out.println((calendar2.getTimeInMillis() - calendar1.getTimeInMillis()) / millisOfDay); ```