Get first and last day of month using threeten, LocalDate

后端 未结 10 2452
鱼传尺愫
鱼传尺愫 2020-12-07 14:06

I have a LocalDate which needs to get the first and last day of the month. How do I do that?

eg. 13/2/2014 I need to get 1/2/2014 and

相关标签:
10条回答
  • 2020-12-07 15:01

    You can try this to avoid indicating custom date and if there is need to display start and end dates of current month:

        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);
    

    Result:

    >     Start of month: 2019-12-01
    >     End of month: 2019-12-30
    
    0 讨论(0)
  • 2020-12-07 15:02

    If anyone comes looking for first day of previous month and last day of previous month:

    public static LocalDate firstDayOfPreviousMonth(LocalDate date) {
            return date.minusMonths(1).withDayOfMonth(1);
        }
    
    
    public static LocalDate lastDayOfPreviousMonth(LocalDate date) {
            return date.withDayOfMonth(1).minusDays(1);
        }
    
    0 讨论(0)
  • 2020-12-07 15:04

    YearMonth

    For completeness, and more elegant in my opinion, see this use of YearMonth class.

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

    For the first & last day of the current month, this becomes:

    LocalDate start = YearMonth.now().atDay(1);
    LocalDate end   = YearMonth.now().atEndOfMonth();
    
    0 讨论(0)
  • 2020-12-07 15:05

    Jon Skeets answer is right and has deserved my upvote, just adding this slightly different solution for completeness:

    import static java.time.temporal.TemporalAdjusters.lastDayOfMonth;
    
    LocalDate initial = LocalDate.of(2014, 2, 13);
    LocalDate start = initial.withDayOfMonth(1);
    LocalDate end = initial.with(lastDayOfMonth());
    
    0 讨论(0)
提交回复
热议问题