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

}


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM