LocalDateTime 获取上个月最后第一天及最后一天

有个需求 如果获取本月一号到昨天 如果今天是1号 获取上月月底到月末   实现如下 

public static void main(String[] args) {

// 如果是1号
//LocalDate localDate = LocalDate.of(2020,11, 1);
LocalDate localDate = LocalDate.of(2020,11, 11);
LocalDateTime localDateTime=null;
LocalDateTime localDateTime2=null;
if(localDate.getDayOfMonth()==1){//1号查询上个月月底到月末
int dayOfMonth = localDate.plusDays(-1).getDayOfMonth();//获取上个月的天数
localDate = localDate.plusDays(-(dayOfMonth));//上一月一号
String date = localDate.getYear() + "-" + localDate.getMonthValue() + "-" + localDate.getDayOfMonth();
date = DateUtil.getDateShort(date);
localDateTime = DateUtil.toLocalDateTime(date + " 00:00:00");
date = localDate.getYear() + "-" + localDate.getMonthValue() + "-" + dayOfMonth;
date = DateUtil.getDateShort(date);
localDateTime2 = DateUtil.toLocalDateTime(date + " 00:00:00");
}else{//一号到昨天
int dayOfMonth = localDate.plusDays(-1).getDayOfMonth();//昨天
String date = localDate.getYear() + "-" + localDate.getMonthValue() + "-" + 1;
date = DateUtil.getDateShort(date);
localDateTime = DateUtil.toLocalDateTime(date + " 00:00:00");
date = localDate.getYear() + "-" + localDate.getMonthValue() + "-" + dayOfMonth;
date = DateUtil.getDateShort(date);
localDateTime2 = DateUtil.toLocalDateTime(date + " 00:00:00");
}

System.out.println(localDateTime);
System.out.println(localDateTime2);

}

原文地址:https://www.cnblogs.com/Mr-Y1907/p/14024286.html