Java教程

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) 用于将指定的时间对象调整为具有今年的月份。
String format(DateTimeFormatter formatter) 它用于使用指定的格式化程序对本月进行格式化。
int get(TemporalField field) 它用于从今年月份中以整数形式获取指定字段的值。
boolean isLeapYear() 根据ISO通用日历系统规则,用于检查年份是否为a年。
static YearMonth now() 用于从默认时区的系统时钟获取当前年月。
static YearMonth of(int year, int month) 它用于从年份和月份中获取YearMonth的实例。
YearMonth plus(TemporalAmount amountToAdd) 它用于返回本月的副本,并添加指定的数量。
YearMonth minus (TemporalAmount amountToSubtract) 它用于返回本月的副本,其中减去指定的数量。

Java YearMonth示例: now()

import java.time.YearMonth;
public class YearMonthExample1 {
    public static void main(String[] args) {
        YearMonth ym = YearMonth.now();
        System.out.println(ym);
    }
}
输出:
2017-01

Java YearMonth示例: format()

import java.time.YearMonth;
import java.time.format.DateTimeFormatter;
public class YearMonthExample2 {
    public static void main(String[] args) {
        YearMonth ym = YearMonth.now();
        String s = ym.format(DateTimeFormatter.ofPattern("MM yyyy"));
        System.out.println(s);
    }
}
输出:
01 2017

Java YearMonth示例: get()

import java.time.YearMonth;
import java.time.temporal.ChronoField;
public class YearMonthExample3 {
    public static void main(String[] args) {
        YearMonth y = YearMonth.now();
        long l1 = y.get(ChronoField.YEAR);
        System.out.println(l1);
        long l2 = y.get(ChronoField.MONTH_OF_YEAR);
        System.out.println(l2);
    }
}
输出:
20171

Java YearMonth示例: plus()

import java.time.*;
public class YearMonthExample4 {
    public static void main(String[] args) {
        YearMonth ym1 = YearMonth.now();
        YearMonth ym2 = ym1.plus(Period.ofYears(2));
        System.out.println(ym2);
    }
}
输出:
2019-01

Java YearMonth示例: minus()

import java.time.*;
public class YearMonthExample5 {
    public static void main(String[] args) {
        YearMonth ym1 = YearMonth.now();
        YearMonth ym2 = ym1.minus(Period.ofYears(2));
        System.out.println(ym2);
    }
}
输出:
2015-01
昵称: 邮箱:
Copyright © 2022 立地货 All Rights Reserved.
备案号:京ICP备14037608号-4