0
1

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.

年数を加算して月末を取得するメソッド

Last updated at Posted at 2019-06-01

Javaで月末を取得をするメソッド


	public static String getLastYmd(String ymd) {
		try {
			//日付チェック
			SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
			sdf.setLenient(false);
			sdf.parse(ymd);

			//年・月を取得する
			int y = Integer.parseInt(ymd.substring(0, 4));
			int m = Integer.parseInt(ymd.substring(4, 6));

			//取得した年月の最終年月日を取得する
			Calendar cal = Calendar.getInstance();
			cal.set(Calendar.YEAR, y);
			cal.set(Calendar.MONTH, m - 1);
			cal.set(Calendar.DAY_OF_MONTH, cal.getActualMaximum(Calendar.DATE));

			//YYYYMMDD形式にして変換して返す
			return sdf.format(cal.getTime());

		} catch (Exception ex) {
			//例外発生時はnullを返す
			return null;
		}
	}

#年数を加算して月末を取得するメソッド

	public static String addYear(String fromYear, int year) {

		// フォーマット変換用のSimpleDateFormatオブジェクトを生成
		DateFormat df = new SimpleDateFormat("yyyyMMdd");

		// 現在日時を保持するCalendarオブジェクトを生成
		Calendar cal = Calendar.getInstance();
		try {
			cal.setTime(df.parse(fromYear));
		} catch (ParseException e) {
			// TODO 自動生成された catch ブロック
			e.printStackTrace();
		}

		// 年数を加算
		cal.add(Calendar.YEAR, year);

		return getLastYmd(df.format(cal.getTime()));
	}
0
1
2

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
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?