LocalDateTime 마지막 날짜 - LocalDateTime majimag naljja

매월 첫날과 마지막 날을 가져와야하는 LocalDate가 있습니다. 어떻게하나요?

Show

    예. 13/2/2014
    내가 얻을 필요가 1/2/201428/2/2014에 LOCALDATE의 형식을 지원합니다.

    Threeten LocalDate 클래스 사용.



    답변

    withDayOfMonth, 및 lengthOfMonth()다음을 사용하십시오 .

    LocalDate initial = LocalDate.of(2014, 2, 13);
    LocalDate start = initial.withDayOfMonth(1);
    LocalDate end = initial.withDayOfMonth(initial.lengthOfMonth());


    답변

    API는 비즈니스 요구 사항과 밀접하게 일치하는 솔루션을 지원하도록 설계되었습니다.

    import static java.time.temporal.TemporalAdjusters.*;
    
    LocalDate initial = LocalDate.of(2014, 2, 13);
    LocalDate start = initial.with(firstDayOfMonth());
    LocalDate end = initial.with(lastDayOfMonth());

    그러나 Jon의 솔루션도 좋습니다.


    답변

    YearMonth

    완성도를 높이고 내 생각에 더 우아한 것을 보려면이 YearMonth클래스 사용을 참조하십시오 .

    YearMonth month = YearMonth.from(date);
    LocalDate start = month.atDay(1);
    LocalDate end   = month.atEndOfMonth();

    이번 달의 첫 번째 및 마지막 날은 다음과 같습니다.

    LocalDate start = YearMonth.now().atDay(1);
    LocalDate end   = YearMonth.now().atEndOfMonth();


    답변

    Jon Skeets의 대답은 옳고 완전성을 위해 약간 다른 솔루션을 추가하는 것뿐입니다.

    import static java.time.temporal.TemporalAdjusters.lastDayOfMonth;
    
    LocalDate initial = LocalDate.of(2014, 2, 13);
    LocalDate start = initial.withDayOfMonth(1);
    LocalDate end = initial.with(lastDayOfMonth());


    답변

    사람이 찾고 오면 이전 달의 첫째 날이전 달의 마지막 날 :

    public static LocalDate firstDayOfPreviousMonth(LocalDate date) {
            return date.minusMonths(1).withDayOfMonth(1);
        }
    
    
    public static LocalDate lastDayOfPreviousMonth(LocalDate date) {
            return date.withDayOfMonth(1).minusDays(1);
        }


    답변

     LocalDate monthstart = LocalDate.of(year,month,1);
     LocalDate monthend = monthstart.plusDays(monthstart.lengthOfMonth()-1);


    답변

    사용자 지정 날짜를 지정하지 않고 이번 달의 시작 및 종료 날짜를 표시해야하는 경우이를 시도 할 수 있습니다.

        LocalDate start = LocalDate.now().minusDays(LocalDate.now().getDayOfMonth()-1);
        LocalDate end = LocalDate.now().minusDays(LocalDate.now().getDayOfMonth()).plusMonths(1);
        System.out.println("Start of month: " + start);
        System.out.println("End of month: " + end);

    결과:

    >     Start of month: 2019-12-01
    >     End of month: 2019-12-30