當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


Java DayOfWeek get()用法及代碼示例


java.time.DayOfWeek的get()方法是Java中的一個內置函數,它以TemporalField作為參數,並從此day-of-week中獲取指定字段的值作為int。 TemporalField是日期時間字段,例如month-of-year或hour-of-minute。日期和時間使用此類字段表示。如果該字段是DAY_OF_WEEK,則將返回day-of-week的值(從1到7)。所有其他ChronoField實例將引發UnsupportedTemporalTypeException。 int值遵循ISO-8601標準,從1(星期一)到7(星期日)。

方法聲明:

public int get(TemporalField field);

用法:


int val = DayOfWeekObject.get(TemporalField field);

參數:此方法將field作為參數,其中:

  • field –是類似Chronafield.DAY_OF_WEEK的時間字段。
  • DayOfWeekObject–表示DayOfWeek對象。

參數:此方法不接受任何參數。

返回值:該函數返回星期幾的int值,例如,星期一為1,星期二為2,依此類推。

以下示例程序旨在說明上述方法:
示例1:

// 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

示例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(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://docs.oracle.com/javase/8/docs/api/java/time/DayOfWeek.html#get-java.time.temporal.TemporalField-



相關用法


注:本文由純淨天空篩選整理自rupesh_rao大神的英文原創作品 DayOfWeek get() method in Java with Examples。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。