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 28/2/2014 in LocalDate formats.
Using threeten LocalDate class.
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 28/2/2014 in LocalDate formats.
Using threeten LocalDate class.
Just use withDayOfMonth
, and lengthOfMonth()
:
LocalDate initial = LocalDate.of(2014, 2, 13);
LocalDate start = initial.withDayOfMonth(1);
LocalDate end = initial.withDayOfMonth(initial.lengthOfMonth());
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.
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();
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());
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
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);
}
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);