我有一个LocalDate需要获得该月的第一天和最后一天。我怎么做?
例如。 13/2/2014我需要以LocalDate格式获得1/2/2014和28/2/2014。
使用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的答案是正确的,并且值得我的upvote,只需添加这个略有不同的完整性解决方案:
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 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);
你可以找到欲望输出,但需要为getLastDayOfMonth方法处理参数true / false
该参数表示闰年
如果你只想用LocalDate类做:
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);