📜  Java8 MonthDay类

📅  最后修改于: 2020-10-01 06:37:14             🧑  作者: Mango

Java MonthDay类

Java MonthDay类是一个不变的日期时间对象,它表示月份和月份的组合。它继承了Object类并实现Comparable接口。

Java MonthDay类声明

我们来看一下java.time.MonthDay类的声明。

public final class MonthDay extends Object 
implements TemporalAccessor, TemporalAdjuster, Comparable, Serializable

Java MonthDay的方法

Method Description
LocalDate atYear(int year) It is used to combine this month-day with a year to create a LocalDate.
String format(DateTimeFormatter formatter) It is used to format this month-day using the specified formatter.
int get(TemporalField field) It is used to get the value of the specified field from this month-day as an int.
boolean isValidYear(int year) It is used to check if the year is valid for this month-day.
static MonthDay now() It is used to obtain the current month-day from the system clock in the default time-zone.
static MonthDay of(int month, int dayOfMonth) It is used to obtain an instance of MonthDay.
ValueRange range(TemporalField field) It is used to get the range of valid values for the specified field.

Java MonthDay类示例

import java.time.*;
public class MonthDayExample1 {
  public static void main(String[] args) {
    MonthDay month = MonthDay.now();
    LocalDate date = month.atYear(1994);
    System.out.println(date);
  }
}

输出:

1994-01-17

Java MonthDay类示例:isValidYear()

import java.time.*;
public class MonthDayExample2 {
  public static void main(String[] args) {
    MonthDay month = MonthDay.now();
    boolean b = month.isValidYear(2012);
    System.out.println(b);
  }
}

输出:

true

Java MonthDay类示例:get()

import java.time.*;
import java.time.temporal.*;
public class MonthDayExample3{
  public static void main(String[] args) {
    MonthDay month = MonthDay.now();
    long n = month.get(ChronoField.MONTH_OF_YEAR);
    System.out.println(n);
  }
}

输出:

1

Java MonthDay类示例:range()

import java.time.*;
import java.time.temporal.*;
public class MonthDayExample4 {
  public static void main(String[] args) {
    MonthDay month = MonthDay.now();
    ValueRange r1 = month.range(ChronoField.MONTH_OF_YEAR);
    System.out.println(r1);
    ValueRange r2 = month.range(ChronoField.DAY_OF_MONTH);
    System.out.println(r2);
  }
}

输出:

1 - 12
1 - 31