Get first and last day of month using threeten, LocalDate

后端 未结 10 2451
鱼传尺愫
鱼传尺愫 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 14:45

    Just here to show my implementation for @herman solution

    ZoneId americaLaPazZone = ZoneId.of("UTC-04:00");
    
    static Date firstDateOfMonth(Date date) {
      LocalDate localDate = convertToLocalDateWithTimezone(date);
      YearMonth baseMonth = YearMonth.from(localDate);
      LocalDateTime initialDate = baseMonth.atDay(firstDayOfMonth).atStartOfDay();
      return Date.from(initialDate.atZone(americaLaPazZone).toInstant());
    }
    
    static Date lastDateOfMonth(Date date) {
      LocalDate localDate = convertToLocalDateWithTimezone(date);
      YearMonth baseMonth = YearMonth.from(localDate);
      LocalDateTime lastDate = baseMonth.atEndOfMonth().atTime(23, 59, 59);
      return Date.from(lastDate.atZone(americaLaPazZone).toInstant());
    }
    
    static LocalDate convertToLocalDateWithTimezone(Date date) {
      return LocalDateTime.from(date.toInstant().atZone(americaLaPazZone)).toLocalDate();
    }
    
    0 讨论(0)
  • 2020-12-07 14:49

    Try this:

    LocalDate initial = LocalDate.of(2014, 2, 13);
    LocalDate start = initial.withDayOfMonth(1);         
    LocalDate end = initial.withDayOfMonth(initial.getMonthOfYear().getLastDayOfMonth(false));
    System.out.println(start);
    System.out.println(end);
    

    you can find the desire output but need to take care of parameter true/false for getLastDayOfMonth method

    that parameter denotes leap year

    0 讨论(0)
  • 2020-12-07 14:50
     LocalDate monthstart = LocalDate.of(year,month,1);
     LocalDate monthend = monthstart.plusDays(monthstart.lengthOfMonth()-1);
    
    0 讨论(0)
  • 2020-12-07 14:55

    Just use withDayOfMonth, and lengthOfMonth():

    LocalDate initial = LocalDate.of(2014, 2, 13);
    LocalDate start = initial.withDayOfMonth(1);
    LocalDate end = initial.withDayOfMonth(initial.lengthOfMonth());
    
    0 讨论(0)
  • 2020-12-07 14:57

    The API was designed to support a solution that matches closely to business requirements

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

    However, Jon's solutions are also fine.

    0 讨论(0)
  • 2020-12-07 14:58

    if you want to do it only with the LocalDate-class:

    LocalDate initial = LocalDate.of(2014, 2, 13);
    
    LocalDate start = LocalDate.of(initial.getYear(), initial.getMonthValue(),1);
    
    // Idea: the last day is the same as the first day of next month minus one day.
    LocalDate end = LocalDate.of(initial.getYear(), initial.getMonthValue(), 1).plusMonths(1).minusDays(1);
    
    0 讨论(0)
提交回复
热议问题