当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


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。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。