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


Java OffsetTime adjustInto()用法及代碼示例


Java中OffsetDateTime類的adjustInto()方法將指定的時間對象調整為與此對象具有相同的時間。

用法:

public Temporal adjustInto(Temporal temporal)

參數:此方法接受單個參數temporal,該參數指定要調整的目標對象,而不是null。


返回值:它返回調整後的對象,不為null

錯誤和異常:此方法引發兩個異常,如下所述:

  • DateTimeException:如果無法進行調整。
  • ArithmeticException:如果發生數字溢出。

以下示例程序旨在說明adjustInto()方法:

示例1:

// Java program to demonstrate the adjustInto() method 
  
import java.time.OffsetTime; 
import java.time.ZonedDateTime; 
  
public class GFG { 
    public static void main(String[] args) 
    { 
  
        // Current time 
        ZonedDateTime date = ZonedDateTime.now(); 
  
        // Prints the current time 
        System.out.println("Current date:" + date); 
  
        // Parsed the date 
        OffsetTime date1 = OffsetTime.parse("14:30:30+05:00"); 
  
        // Adjusts 
        date = (ZonedDateTime)date1.adjustInto(date); 
        System.out.println("Adjusted date:" + date); 
    } 
}
輸出:
Current date:2018-12-11T10:01:37.877Z[Etc/UTC]
Adjusted date:2018-12-11T14:30:30Z[Etc/UTC]

程序2

// Java program to demonstrate the adjustInto() 
// method exceptions 
  
import java.time.OffsetTime; 
import java.time.ZonedDateTime; 
  
public class GFG { 
    public static void main(String[] args) 
    { 
        try { 
            // Current time 
            // Current time 
            ZonedDateTime date = ZonedDateTime.now(); 
  
            // Prints the current time 
            System.out.println("Current date:" + date); 
  
            // Parsed the date 
            OffsetTime date1 = OffsetTime.parse("25:30:30+05:00"); 
  
            // Adjusts 
            date = (ZonedDateTime)date1.adjustInto(date); 
            System.out.println("Adjusted date:" + date); 
        } 
        catch (Exception e) { 
            System.out.println(e); 
        } 
    } 
}
輸出:
Current date:2018-12-11T10:01:42.520Z[Etc/UTC]
java.time.format.DateTimeParseException: Text '25:30:30+05:00' could not be parsed: Invalid value for HourOfDay (valid values 0 - 23): 25

參考: https://docs.oracle.com/javase/8/docs/api/java/time/OffsetTime.html#adjustInto-java.time.temporal.Temporal-



相關用法


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