mục lục
Java Ngày cuối thángLấy Calendar.getActualMaximum()
JavaNgày được chỉ địnhNgày cuối thángĐây là một chương trình mẫu để thu thập [dữ liệu].
java.util.Calendarlớp họcgetActualMaximum(Calendar.DATE)でNgày cuối thángBạn có thể có được nó.
Chương trình mẫu
/**
* 指定した日付文字列(yyyy/MM/dd or yyyy-MM-dd)
* における月末日付を返します。
*
* @param strDate 対象の日付文字列
* @return 月末日付
*/
public static int getLastDay(String strDate) {
if (strDate == null || strDate.length() != 10) {
throw new IllegalArgumentException(
"引数の文字列["+ strDate +"]" +
"は不正です。");
}
int yyyy = Integer.parseInt(strDate.substring(0,4));
int MM = Integer.parseInt(strDate.substring(5,7));
int dd = Integer.parseInt(strDate.substring(8,10));
Calendar cal = Calendar.getInstance();
cal.set(yyyy,MM-1,dd);
int last = cal.getActualMaximum(Calendar.DATE);
return last;
}
Kết quả thực thi
◆Ví dụ
public static void main(String[] args) { System.out.println(getLastDay("2007/01/01")); System.out.println(getLastDay("2007/02/01")); System.out.println(getLastDay("2008/02/01")); }
◆Kết quả đầu ra
31 28 29
*Vì năm 2008 là năm nhuận, nên ngày cuối cùng của tháng Hai là ngày 29.
