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


Java ChronoLocalDateTime with(TemporalField, long)用法及代码示例


ChronoLocalDateTime接口的with(TemporalField字段,long newValue)方法用于将ChronoLocalDateTime的指定字段设置为新值,并返回新时间的副本。此方法可用于更改任何受支持的字段,例如年,日,月,小时,分钟或秒。如果由于不支持该字段或其他原因而无法设置新值,则会引发异常。该ChronoLocalDateTime实例是不可变的,不受此方法调用的影响。

用法:

ChronoLocalDateTime with(TemporalField field, long newValue)

参数:此方法接受作为结果中要设置的字段的field和作为结果中该字段的新值的newValue。


返回值:此方法基于此方法返回ChronoLocalDateTime并带有指定的字段集。

异常:此方法引发以下异常:

  • DateTimeException-如果无法进行调整。
  • UnsupportedTemporalTypeException-如果不支持该字段。
  • ArithmeticException-如果发生数字溢出。

以下示例程序旨在说明with()方法:

程序1:

// Java program to demonstrate 
// ChronoLocalDateTime.with() method 
  
import java.time.*; 
import java.time.chrono.*; 
import java.time.temporal.*; 
  
public class GFG { 
    public static void main(String[] args) 
    { 
  
        // create ChronoLocalDateTime object 
        ChronoLocalDateTime time 
            = LocalDateTime 
                  .parse("2019-12-31T19:15:30"); 
  
        // print instance 
        System.out.println("ChronoLocalDateTime before"
                           + " adjustment:"
                           + time); 
  
        // apply with method of ChronoLocalDateTime 
        ChronoLocalDateTime updatedlocal 
            = time.with(ChronoField.YEAR, 2017); 
  
        // print instance 
        System.out.println("ChronoLocalDateTime after"
                           + " adjustment:"
                           + updatedlocal); 
    } 
}
输出:
ChronoLocalDateTime before adjustment:2019-12-31T19:15:30
ChronoLocalDateTime after adjustment:2017-12-31T19:15:30

程序2:

// Java program to demonstrate 
// ChronoLocalDateTime.with() method 
  
import java.time.*; 
import java.time.chrono.*; 
import java.time.temporal.*; 
  
public class GFG { 
    public static void main(String[] args) 
    { 
  
        // create ChronoLocalDateTime object 
        ChronoLocalDateTime time 
            = LocalDateTime 
                  .parse("2018-10-25T23:12:31.123"); 
  
        // print instance 
        System.out.println("ChronoLocalDateTime before"
                           + " adjustment:"
                           + time); 
  
        // apply with method of ChronoLocalDateTime 
        ChronoLocalDateTime updatedlocal 
            = time.with(ChronoField.MONTH_OF_YEAR, 1); 
  
        // print instance 
        System.out.println("ChronoLocalDateTime after"
                           + " adjustment:"
                           + updatedlocal); 
    } 
}
输出:
ChronoLocalDateTime before adjustment:2018-10-25T23:12:31.123
ChronoLocalDateTime after adjustment:2018-01-25T23:12:31.123

参考: https://docs.oracle.com/javase/9/docs/api/java/time/chrono/ChronoLocalDateTime.html#with-java.time.temporal.TemporalField-long-



相关用法


注:本文由纯净天空筛选整理自srinam大神的英文原创作品 ChronoLocalDateTime with(TemporalField, long) method in Java with Examples。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。