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