YearMonth
是Java 8引入的java.time
包中的一部分,它是用来表示特定年份和月份组合的一个不可变类。这个类对于处理那些只需要关注年和月而不需要具体到日的时间情景非常有用,例如计算某个月有多少天、表示信用卡的到期日期、处理财政年度报告等。
主要特点:
不可变性:一旦创建,
YearMonth
对象就不能被修改,这使得它们线程安全且易于在多线程环境中使用。ISO标准:它遵循ISO-8601日历系统,即年份总是四位数,月份从1(一月)到12(十二月)。
方法丰富:提供了多种方法来操作年月数据,包括获取月份的天数、比较年月、调整到指定的年或月、格式化输出等。
Comparable:实现了
Comparable<YearMonth>
接口,可以直接比较两个YearMonth
实例的先后顺序。
常用方法:
YearMonth
是 Java 中一个专门表示年份和月份的类,它位于 java.time
包中。它是不可变的,表示特定年份和月份的对象,例如2023年5月。这个类没有时区和时间的概念,只关注年和月。
创建 YearMonth 对象
可以使用静态工厂方法创建 YearMonth
实例:
// 使用当前日期的年份和月份
YearMonth currentYearMonth = YearMonth.now();
// 指定年份和月份
YearMonth specificYearMonth = YearMonth.of(2023, 5);
// 从字符串解析
YearMonth parsedYearMonth = YearMonth.parse("2023-05");
常用方法
YearMonth
提供了一些常用方法来操作和查询年份和月份:
获取年份和月份
int year = currentYearMonth.getYear(); // 获取年份
int month = currentYearMonth.getMonthValue(); // 获取月份(1到12)
调整年份和月份
YearMonth nextMonth = currentYearMonth.plusMonths(1); // 增加一个月
YearMonth previousYear = currentYearMonth.minusYears(1); // 减少一年
比较
boolean isBefore = specificYearMonth.isBefore(YearMonth.of(2024, 1)); // 是否在指定年月之前
boolean isAfter = specificYearMonth.isAfter(YearMonth.of(2022, 12)); // 是否在指定年月之后
计算天数
可以计算某个月份的天数:
int daysInMonth = specificYearMonth.lengthOfMonth(); // 获取月份的天数
格式化
可以将 YearMonth
对象格式化为字符串:
String formattedYearMonth = specificYearMonth.toString(); // 默认格式为 "YYYY-MM"
示例代码
以下是一个完整的示例代码,展示了 YearMonth
的一些用法:
public class YearMonthExample {
public static void main(String[] args) {
// 创建 YearMonth 实例
YearMonth currentYearMonth = YearMonth.now();
YearMonth specificYearMonth = YearMonth.of(2023, 5);
YearMonth parsedYearMonth = YearMonth.parse("2023-05");
// 获取年份和月份
int year = specificYearMonth.getYear();
int month = specificYearMonth.getMonthValue();
// 调整年份和月份
YearMonth nextMonth = currentYearMonth.plusMonths(1);
YearMonth previousYear = currentYearMonth.minusYears(1);
// 比较 YearMonth
boolean isBefore = specificYearMonth.isBefore(YearMonth.of(2024, 1));
boolean isAfter = specificYearMonth.isAfter(YearMonth.of(2022, 12));
// 计算月份的天数
int daysInMonth = specificYearMonth.lengthOfMonth();
// 格式化 YearMonth
String formattedYearMonth = specificYearMonth.toString();
// 输出结果
System.out.println("当前年月: " + currentYearMonth);
System.out.println("指定年月: " + specificYearMonth);
System.out.println("解析年月: " + parsedYearMonth);
System.out.println("年份: " + year);
System.out.println("月份: " + month);
System.out.println("下个月: " + nextMonth);
System.out.println("上一年: " + previousYear);
System.out.println("是否在2024-01之前: " + isBefore);
System.out.println("是否在2022-12之后: " + isAfter);
System.out.println("2023-05的天数: " + daysInMonth);
System.out.println("格式化后的年月: " + formattedYearMonth);
}
}
通过 YearMonth
类,处理年月信息变得更加方便和直观,特别是在不需要时间和时区信息的情况下。