Java 获取上个月的年月:使用 YearMonth 和 TemporalAdjusters
Java 获取上个月的年月:使用 YearMonth 和 TemporalAdjusters
本文介绍了如何使用 Java 的 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() 方法获取给定年月的第一天,然后再减去一个月来得到上个月的年月。
原文地址: https://www.cveoy.top/t/topic/qDwN 著作权归作者所有。请勿转载和采集!