在Java中,Calendar類用于操作和處理日期和時間。以下是Calendar類的一些常用方法和用法:
Calendar calendar = Calendar.getInstance();
Date currentDate = calendar.getTime();
calendar.set(Calendar.YEAR, 2021);
calendar.set(Calendar.MONTH, Calendar.JANUARY);
calendar.set(Calendar.DAY_OF_MONTH, 1);
calendar.set(Calendar.HOUR_OF_DAY, 12);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
int year = calendar.get(Calendar.YEAR);
int month = calendar.get(Calendar.MONTH);
int dayOfMonth = calendar.get(Calendar.DAY_OF_MONTH);
int hourOfDay = calendar.get(Calendar.HOUR_OF_DAY);
int minute = calendar.get(Calendar.MINUTE);
int second = calendar.get(Calendar.SECOND);
calendar.add(Calendar.YEAR, 1); // 增加一年
calendar.add(Calendar.MONTH, -1); // 減少一個月
calendar.add(Calendar.DAY_OF_MONTH, 7); // 增加7天
int maxDayOfMonth = calendar.getActualMaximum(Calendar.DAY_OF_MONTH); // 獲取當月的最大天數(shù)
int maxWeekOfYear = calendar.getActualMaximum(Calendar.WEEK_OF_YEAR); // 獲取當年的最大周數(shù)
boolean isLeapYear = calendar.isLeapYear(year);
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String formattedDate = dateFormat.format(calendar.getTime());
以上是Calendar類的一些常用方法和用法,可以根據(jù)實際需求選擇合適的方法來操作和處理日期和時間。