Java Month枚举
在Java中,Month是代表一年中12个月的枚举。除了文本枚举名称外,每年的每个月都有一个int值。
Java月枚举声明
让我们看看java.time.Month的声明。
public enum Month extends Enum<Month>implements TemporalAccessor, TemporalAdjuster
Java月的方法
方法 |
说明 |
int getValue() |
用于获取一年中月份的int值 |
int get(TemporalField field) |
用于从一年中的这个月中获取指定字段的值作为整数。 |
int length(boolean leapYear) |
它用来获取本月的天数。 |
int maxLength() |
它用于获取本月的最大长度(天)。 |
int minLength() |
它用于获取本月的最小长度(天)。 |
Month minus(long months) |
它用于返回一年中的月份,即该月份之前的指定月份。 |
Month plus(long months) |
用于返回一年中的月份,该月份是该季度之后指定的季度数。 |
static Month of(int month) |
用于从int值获取Month的实例。 |
Java月枚举示例
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月枚举示例: 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());
}
}
输出:
Java月枚举示例: 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));
}
}
输出:
Java月枚举示例: 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));
}
}
输出:
Java月枚举示例: 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));
}
}
输出: