Java日期时间 – Java年月日
年
年表示一年,例如2012年,2013年等。
以下代码显示如何创建Year对象并对其执行基本操作。
import java.time.Year;
public class Main {
public static void main(String[] args) {
Year y1 = Year.of(2014);
System.out.println(y1);
Year y2 = y1.minusYears(1);
System.out.println(y2);
Year y3 = y1.plusYears(1);
System.out.println(y3);
Year y4 = Year.now();
System.out.println(y4);
if (y1.isLeap()) {
System.out.println(y1 + " is a leap year.");
} else {
System.out.println(y1 + " is not a leap year.");
}
}
}
上面的代码生成以下结果。
年月
年月表示年和月的有效组合,例如2012-05,2013-09等。
以下代码显示了如何创建Year Month对象并对其执行一些基本操作。
import java.time.Month;
import java.time.YearMonth;
public class Main {
public static void main(String[] args) {
YearMonth ym1 = YearMonth.of(2014, Month.JUNE);
int monthLen = ym1.lengthOfMonth();
System.out.println(monthLen);
int yearLen = ym1.lengthOfYear();
System.out.println(yearLen);
}
}
上面的代码生成以下结果。

月
Month 枚举有12个常量来表示12个月。
常量名称为 一月,二月,三月,四月,五月,六月,七月,八月,九月,十月,十一月和十二月。
Month 枚举从1到12按顺序编号,其中一月为1,十二月为12。
Month枚举从int值创建一个Month实例。
我们可以使用from()从date对象创建Month。
要获取Month的int值,请使用Month枚举 getValue()方法。
import java.time.LocalDate;
import java.time.Month;
public class Main {
public static void main(String[] args) {
LocalDate localDate = LocalDate.of(2014, Month.AUGUST, 3);
System.out.println(localDate);
Month month1 = Month.from(localDate);
System.out.println(month1);
Month month2 = Month.of(2);
System.out.println(month2);
Month month3 = month2.plus(2);
System.out.println(month3);
Month month4 = localDate.getMonth();
System.out.println(month4);
int monthIntValue = month2.getValue();
System.out.println(monthIntValue);
}
}
上面的代码生成以下结果。
月日
MonthDay表示一个月和一个月中某一天的有效组合,例如12-15。
以下代码显示了如何创建MonthDay对象并对其执行基本操作。
import java.time.Month;
import java.time.MonthDay;
public class Main {
public static void main(String[] args) {
MonthDay md1 = MonthDay.of(Month.DECEMBER, 25);
MonthDay md2 = MonthDay.of(Month.FEBRUARY, 29);
if (md2.isValidYear(2014)) {
System.out.println(md2);
}
System.out.println(md1.getDayOfMonth());
}
}
上面的代码生成以下结果。
DayOfWeek
DayOfWeek 枚举定义七个常量来表示一周中的七天。
DayOfWeek 枚举的常量是 MONDAY,TUESDAY,WEDNESDAY,THURSDAY,FRIDAY,SATURDAY和SUNDAY 。
后端的int值为1到7。1表示星期一,2表示星期二…
以下代码显示了如何使用DayOfWeek枚举。
import java.time.DayOfWeek;
import java.time.LocalDate;
public class Main {
public static void main(String[] args) {
LocalDate localDate = LocalDate.of(2014, 6, 21);
System.out.println(localDate);
DayOfWeek dayOfWeek1 = DayOfWeek.from(localDate);
System.out.println(dayOfWeek1);
int intValue = dayOfWeek1.getValue();
System.out.println(intValue);
DayOfWeek dayOfWeek2 = localDate.getDayOfWeek();
System.out.println(dayOfWeek2);
DayOfWeek dayOfWeekFromInteger = DayOfWeek.of(7);
System.out.println(dayOfWeekFromInteger);
DayOfWeek dayOfWeekAdded = dayOfWeekFromInteger.plus(1);
System.out.println(dayOfWeekAdded);
DayOfWeek dayOfWeekSubtracted = dayOfWeekFromInteger.minus(2);
System.out.println(dayOfWeekSubtracted);
}
}
上面的代码生成以下结果。


国外主机测评 - 国外VPS,国外服务器,国外云服务器,测评及优惠码













