1
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 1 year has passed since last update.

Java Timeで月末日を取得する

Posted at

TL; DR

java.time.temporal.TemporalAdjusters.lastDayOfMonth() を使う。

実証コード 

// Java
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;

import static java.time.temporal.TemporalAdjusters.lastDayOfMonth;

public class Test {
    public static void main(String[] args) {
        LocalDate date1 = LocalDate.of(2023, 2, 15);
        LocalDate date2 = LocalDate.of(2024, 2, 15);

        System.out.println(date1.with(lastDayOfMonth()).format(DateTimeFormatter.ISO_LOCAL_DATE));
        System.out.println(date2.with(lastDayOfMonth()).format(DateTimeFormatter.ISO_LOCAL_DATE));
    }
}
// Kotlin
import java.time.LocalDate
import java.time.format.DateTimeFormatter
import java.time.temporal.TemporalAdjusters.lastDayOfMonth

object Test {
    @JvmStatic
    fun main(args: Array<String>) {
        val date1 = LocalDate.of(2023, 2, 15)
        val date2 = LocalDate.of(2024, 2, 15)

        println(date1.with(lastDayOfMonth()).format(DateTimeFormatter.ISO_LOCAL_DATE))
        println(date2.with(lastDayOfMonth()).format(DateTimeFormatter.ISO_LOCAL_DATE))
    }
}

出力結果

2023-02-28
2024-02-29  // うるう年も自動で計算してくれます

他にも

  • firstDayOfMonth(): 月初日の取得
  • firstDayOfNextMonth(): 翌月の初日を取得
  • firstDayOfYear(): その年の1月1日を取得
  • lastDayOfYear(): その年の12月31日を取得
  • firstDayOfNextYear(): 翌年の1月1日を取得
  • firstInMonth(DayOfWeek dayOfWeek): その月の最初の dayOfWeek にあたる日を取得
  • lastInMonth(DayOfWeek dayOfWeek): その月の最後の dayOfWeek にあたる日を取得
  • dayOfWeekInMonth(int ordinal, DayOfWeek dayOfWeek): その月の ordinal 週目の dayOfWeek にあたる日を取得
  • next(DayOfWeek dayOfWeek): その日の次の dayOfWeek にあたる日を取得
  • nextOrSame(DayOfWeek dayOfWeek): その日と同じか、次の dayOfWeek にあたる日を取得
  • previous(DayOfWeek dayOfWeek): その日の前の dayOfWeek にあたる日を取得
  • previousOrSame(DayOfWeek dayOfWeek): その日と同じか、前の dayOfWeek にあたる日を取得
1
1
0

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