Java教程-Java YearMonth类

Java YearMonth类
Java YearMonth类是一个不可变的日期时间对象,用于表示年份和月份的组合。它继承自Object类并实现了Comparable接口。
Java YearMonth类声明
让我们看一下java.time.YearMonth类的声明。
public final class YearMonth extends Object
implements Temporal, TemporalAdjuster, Comparable<YearMonth>, Serializable
Java YearMonth的方法
方法 | 描述 |
---|---|
Temporal adjustInto(Temporal temporal) | 调整指定的时间对象,使其具有与此YearMonth相同的年份和月份。 |
String format(DateTimeFormatter formatter) | 使用指定的格式化程序对此YearMonth进行格式化。 |
int get(TemporalField field) | 从此YearMonth中获取指定字段的值。 |
boolean isLeapYear() | 根据ISO纪元历法规则,检查年份是否为闰年。 |
static YearMonth now() | 从系统时钟中以默认时区获取当前YearMonth。 |
static YearMonth of(int year, int month) | 使用年份和月份获取YearMonth的实例。 |
YearMonth plus(TemporalAmount amountToAdd) | 返回此YearMonth的副本,增加指定的时间量。 |
YearMonth minus(TemporalAmount amountToSubtract) | 返回此YearMonth的副本,减去指定的时间量。 |
LocalDate atEndOfMonth() | 返回月份的最后一天的LocalDate。 |
int compareTo(YearMonth other) | 将此YearMonth与另一个YearMonth进行比较。 |
boolean equals(Object obj) | 检查此YearMonth是否与另一个YearMonth相等。 |
static YearMonth now(Clock clock) | 从指定的时钟获取当前YearMonth。 |
static YearMonth of(int year, int month) | 使用年份和月份获取YearMonth的实例。 |
long until(Temporal endExclusive, TemporalUnit unit) | 根据指定的单位计算到另一个YearMonth的时间量。 |
YearMonth withMonth(int month) | 返回此YearMonth的副本,更改为指定的月份。 |
YearMonth withYear(int year) | 返回此YearMonth的副本,更改为指定的年份。 |
Java YearMonth示例:now()
YearMonthExample1.java
import java.time.*;
public class YearMonthExample1 {
public static void main(String[] args) {
YearMonth yearMonth = YearMonth.now();
System.out.println(yearMonth);
}
}
输出:
2017-01
Java YearMonth示例:format()
YearMonthExample2.java
import java.time.*;
import java.time.format.DateTimeFormatter;
public class YearMonthExample2 {
public static void main(String[] args) {
YearMonth yearMonth = YearMonth.now();
String formatted = yearMonth.format(DateTimeFormatter.ofPattern("MM yyyy"));
System.out.println(formatted);
}
}
输出:
01 201