Java中的 DayOfWeek get() 方法及示例
Java .time.DayOfWeek的get()方法是Java中的一个内置函数,它以TemporalField作为参数,并从该星期几获取指定字段的值作为 int。 TemporalField 是日期时间字段,例如月份或分钟。日期和时间使用此类字段表示。如果该字段为 DAY_OF_WEEK,则将返回从 1 到 7 的星期几的值。所有其他 ChronoField 实例将抛出 UnsupportedTemporalTypeException。 int 值遵循 ISO-8601 标准,从 1(星期一)到 7(星期日)。
方法声明:
public int get(TemporalField field);
句法:
int val = DayOfWeekObject.get(TemporalField field);
参数:此方法将字段作为参数,其中:
参数:此方法不接受任何参数。
返回值:函数返回星期几的int值,例如1代表星期一,2代表星期二,以此类推。
下面的程序说明了上述方法:
方案一:
// Java Program Demonstrate get()
// method of DayOfWeek
import java.time.*;
import java.time.DayOfWeek;
import java.time.temporal.ChronoField;
class DayOfWeekExample {
public static void main(String[] args)
{
// Set a local date whose day is found
LocalDate localDate
= LocalDate.of(1947,
Month.AUGUST, 15);
// Find the day from the local date
DayOfWeek dayOfWeek
= DayOfWeek.from(localDate);
// Printing the day of the week
// and its Int value
System.out.println("Day of the Week on "
+ localDate + " - "
+ dayOfWeek.name());
int val
= dayOfWeek.get(ChronoField.DAY_OF_WEEK);
System.out.println("Int Value of "
+ dayOfWeek.name()
+ " - " + val);
}
}
输出:
Day of the Week on 1947-08-15 - FRIDAY
Int Value of FRIDAY - 5
方案二:
// Java Program Demonstrate get()
// method of DayOfWeek
import java.time.*;
import java.time.DayOfWeek;
import java.time.temporal.ChronoField;
class DayOfWeekExample {
public static void main(String[] args)
{
// Set a local date whose day is found
LocalDate localDate
= LocalDate.of(2015,
Month.JULY, 13);
// Find the day from the local date
DayOfWeek dayOfWeek
= DayOfWeek.from(localDate);
// Printing the day of the week
// and its Int value
System.out.println("Day of the Week on "
+ localDate + " - "
+ dayOfWeek.name());
int val
= dayOfWeek.get(ChronoField.DAY_OF_WEEK);
System.out.println("Int Value of "
+ dayOfWeek.name()
+ " - " + val);
}
}
输出:
Day of the Week on 2015-07-13 - MONDAY
Int Value of MONDAY - 1
参考: https: Java/time/DayOfWeek.html#get-java.time.temporal.TemporalField-