第一种方式 : LocalDate 方式 JAVA8
public static void main(String[] args) {
// LocalDate now = LocalDate.now(); 当日日期
String curMonthdate = "2024-01-05";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
// 将字符串转换为 LocalDate 对象
LocalDate date = LocalDate.parse(curMonthdate, formatter);
LocalDate startOfMonthDate = date.with(TemporalAdjusters.firstDayOfMonth()); // 月初
LocalDate endOfMonthDate = date.with(TemporalAdjusters.lastDayOfMonth()); // 月末
String startOfMonthTime = startOfMonthDate.toString();
String endOfMonthTime = endOfMonthDate.toString();
System.out.println("月初===" + startOfMonthTime);
System.out.println("月末===" + endOfMonthTime);
}
第二种方式:Calendar 方式
public static void main(String[] args) {
String curMonthdate = "2024-01-05";
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
try {
Date date = format.parse(curMonthdate);
Calendar calendar = Calendar.getInstance();
calendar.setTime(date); // 设置指定日期值
calendar.set(Calendar.DAY_OF_MONTH, 1); // 指定月份的1号
String monthFirst = format.format(calendar.getTime());
System.out.println("月初 === " + monthFirst);
// 月初 加一个月 再 减去一天
calendar.add(Calendar.MONTH,1); // 加一个月
calendar.add(Calendar.DAY_OF_MONTH,-1); // 加一个月减一天
String monthLast = format.format(calendar.getTime());
System.out.println("月末 === " + monthLast);
} catch (ParseException e) {
throw new RuntimeException(e);
}
}
06-28
422
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
06-13
480
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
05-22
814
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
01-16
3538
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
05-19