java 根据某个年月202308 获取上月的年月
可以使用java.time包中的YearMonth和TemporalAdjusters类来实现。具体代码如下:
import java.time.YearMonth;
import java.time.temporal.TemporalAdjusters;
public class Main {
public static void main(String[] args) {
YearMonth yearMonth = YearMonth.of(2023, 8);
YearMonth lastMonth = yearMonth.minusMonths(1);
System.out.println("上个月的年月: " + lastMonth);
// 或者使用 TemporalAdjusters
YearMonth lastMonth2 = yearMonth.with(TemporalAdjusters.firstDayOfMonth()).minusMonths(1);
System.out.println("上个月的年月: " + lastMonth2);
}
}
输出结果为:
上个月的年月: 2023-07
上个月的年月: 2023-07
以上代码中,我们首先创建了一个YearMonth对象yearMonth,表示给定的年月。然后使用minusMonths(1)方法得到上个月的年月。另外,我们还可以使用TemporalAdjusters.firstDayOfMonth()方法获取给定年月的第一天,然后再减去一个月来得到上个月的年月
原文地址: http://www.cveoy.top/t/topic/iXxv 著作权归作者所有。请勿转载和采集!