9
7

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Java 指定年月の最終日取得

Last updated at Posted at 2016-02-03

はじめに

事前に準備する外部ライブラリ等はありません。
JavaSEに含まれるjava.util.Calendarクラスを使用します。

実装例

サンプルでは、動作確認しやすいようにmainメソッドで実行できるようにしてあります。
→[2016/02/04追記]yuichiro76さんにご教示いただいた効率のよい方法(Calendar#getActualMaximum)に修正しました。ありがとうございました!

LastDayGetter.java
import java.util.Calendar;

/**
 *
 * @author tool-taro.com
 */
public class LastDayGetter {

	public static void main(String[] args) {

		//対象年
		int year = 2016;
		//対象月
		int month = 2;

		//取得処理
		Calendar calendar = Calendar.getInstance();
		calendar.set(Calendar.YEAR, year);
		calendar.set(Calendar.MONTH, month - 1);
		int result = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
		//標準出力
		System.out.format("取得結果=%1$d", result);
	}
}

動作確認

$ javac LastDayGetter.java
$ java LastDayGetter
$ 取得結果=29

環境

  • 開発

    • Windows 10 Pro
    • JDK 1.8.0_112
    • NetBeans IDE 8.2
  • 動作検証

    • CentOS Linux release 7.2
    • JDK 1.8.0_112

Webツールも公開しています。
Web便利ツール@ツールタロウ

9
7
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
9
7

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?