📜  Java8 Month枚举

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

Java Month枚举

在Java中,Month是代表一年中12个月的枚举。除文本枚举名称外,每年的每个月都有一个int值。

Java Month枚举声明

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

public enum Month extends Enum implements TemporalAccessor, TemporalAdjuster

Java月的方法

Method Description
int getValue() It is used to get the month-of-year int value
int get(TemporalField field) It is used to get the value of the specified field from this month-of-year as an int.
int length(boolean leapYear) It is used to get the length of this month in days.
int maxLength() It is used to get the maximum length of this month in days.
int minLength() It is used to get the minimum length of this month in days.
Month minus(long months) It is used to return the month-of-year that is the specified number of months before this one.
Month plus(long months) It is used to return the month-of-year that is the specified number of quarters after this one.
static Month of(int month) It is used to obtain an instance of Month from an int value.

Java Month枚举示例

import java.time.*;
import java.time.temporal.*;
public class MonthEnumExample1 {
    public static void main(String[] args) {
        Month month = Month.valueOf("January".toUpperCase());
        System.out.printf("For the month of %s all Sunday are:%n", month);
        LocalDate localdate = Year.now().atMonth(month).atDay(1).
        with(TemporalAdjusters.firstInMonth(DayOfWeek.SUNDAY));
        Month mi = localdate.getMonth();
        while (mi == month) {
            System.out.printf("%s%n", localdate);
            localdate = localdate.with(TemporalAdjusters.next(DayOfWeek.SUNDAY));
            mi = localdate.getMonth();
        }
    }
}

输出:

For the month of JANUARY all Sunday are:
2017-01-01
2017-01-08
2017-01-15
2017-01-22
2017-01-29

Java Month枚举示例:getValue()

import java.time.*;
public class MonthEnumExample2 {
  public static void main(String[] args) {
    Month month = Month.from(LocalDate.now());
    System.out.println(month.getValue());
    System.out.println(month.name());
  }
}

输出:

1
JANUARY

Java Month枚举示例:minus()

import java.time.*;
public class MonthEnumExample3 {
  public static void main(String[] args) {
    Month month = Month.from(LocalDate.now());  
    System.out.println(month.minus(2));
  }
}

输出:

NOVEMBER

Java Month枚举示例:plus()

import java.time.*;
public class MonthEnumExample4 {
  public static void main(String[] args) {
    Month month = Month.from(LocalDate.now());  
    System.out.println(month.plus(2));
  }
}

输出:

MARCH

Java Month枚举示例:length()

import java.time.*;
public class MonthEnumExample5 {
  public static void main(String[] args) {
    Month month = Month.from(LocalDate.now());  
    System.out.println("Total Number of days: "+month.length(true));
  }
}

输出:

Total Number of days: 31