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


Java LocalDate withDayOfYear()用法及代碼示例


Java中LocalDate類的withDayOfYear()方法返回已更改day-of-year的此LocalDate的副本。

用法:

public LocalDate withDayOfYear(int dayOfYear)

參數:此方法接受必需的參數dayOfYear,該參數指定要在結果中設置的day-of-year,範圍為1至365-366。


返回值:該函數基於此日期和所請求的日期返回LocalDate,而不是null。

異常:當day-of-year值無效時,該函數引發DateTimeException。

以下示例程序旨在說明LocalDate.withDayOfYear()方法:

示例1:

// Program to illustrate the withDayOfYear() method 
  
import java.util.*; 
import java.time.*; 
  
public class GfG { 
    public static void main(String[] args) 
    { 
  
        // Parses the date 
        LocalDate dt1 = LocalDate.parse("2018-12-07"); 
        LocalDate result = dt1.withDayOfYear(01); 
  
        // Prints the date with year 
        System.out.println("The date with day of year is: " + result); 
    } 
}
輸出:
The date with day of year is: 2018-01-01

示例2:

// Program to illustrate the withDayOfYear() method 
// Exceptions 
import java.util.*; 
import java.time.*; 
import java.time.temporal.ChronoField; 
  
public class GfG { 
    public static void main(String[] args) 
    { 
  
        try { 
            // Parses the date 
            LocalDate dt1 = LocalDate.parse("2018-12-07"); 
            LocalDate result = dt1.withDayOfYear(370); 
  
            // Prints the date with year 
            System.out.println("The date with month is: " + result); 
        } 
        catch (Exception e) { 
            System.out.println(e); 
        } 
    } 
}
輸出:
java.time.DateTimeException: Invalid value for DayOfYear (valid values 1 - 365/366): 370

參考: https://docs.oracle.com/javase/10/docs/api/java/time/LocalDate.html#withDayOfYear(int)



相關用法


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