Java ZonedDateTime withNano()方法及示例

Java ZonedDateTime withNano()方法及示例

withNano() 方法是 ZonedDateTime 类的一个方法,用来改变这个ZonedDateTime中的纳秒数,并在此操作后返回ZonedDateTime的副本。这个方法在本地时间线上操作,改变本地日期时间的时间,在此操作后,本地日期时间被转换回ZonedDateTime,使用区域ID来获得偏移。当转换回ZonedDateTime时,如果本地日期时间处于重叠状态,那么可能的话将保留偏移量,否则,将使用较早的偏移量。这个实例是不可改变的,不受这个方法调用的影响。

语法

public ZonedDateTime withNano(int nanoOfSecond)

参数: 该方法接受一个参数nanoOfSecond,代表要在结果中设置的纳秒数,0到999,999,999。

返回值: 该方法返回一个基于该日期时间的ZonedDateTime,该日期时间具有要求的nanoOfSecond。

异常: 如果nanoOfSecond值无效,该方法会抛出DateTimeException。

下面的程序说明了withNano()方法:

程序1 :

// Java program to demonstrate
// ZonedDateTime.withNano() method
  
import java.time.*;
  
public class GFG {
    public static void main(String[] args)
    {
  
        // create a ZonedDateTime object
        ZonedDateTime zoneddatetime
            = ZonedDateTime.parse(
                "2018-12-06T19:21:12.123+05:30[Asia/Calcutta]");
  
        // print instance
        System.out.println("ZonedDateTime before"
                           + " alter nanoOfSecond: "
                           + zoneddatetime);
  
        // alter nanoOfSecond to 12345987
        ZonedDateTime returnvalue
            = zoneddatetime.withNano(12345987);
  
        // print result
        System.out.println("ZonedDateTime after "
                           + "alter nanoOfSecond: "
                           + returnvalue);
    }
}

输出。

ZonedDateTime before alter nanoOfSecond: 2018-12-06T19:21:12.123+05:30[Asia/Calcutta]  
ZonedDateTime after alter nanoOfSecond: 2018-12-06T19:12.012345987+05:30[Asia/Calcutta]

程序2 :

// Java program to demonstrate
// ZonedDateTime.withNano() method
  
import java.time.*;
  
public class GFG {
    public static void main(String[] args)
    {
  
        // create a ZonedDateTime object
        ZonedDateTime zoneddatetime
            = ZonedDateTime.parse(
                "2018-10-25T23:12:31.123+02:00[Europe/Paris]");
  
        // print instance
        System.out.println("ZonedDateTime before"
                           + " alter nanoOfSecond: "
                           + zoneddatetime);
  
        // alter nanoOfSecond to 439990000
        ZonedDateTime returnvalue
            = zoneddatetime.withNano(439990000);
  
        // print result
        System.out.println("ZonedDateTime after "
                           + "alter nanoOfSecond: "
                           + returnvalue);
    }
}

输出。

ZonedDateTime before alter nanoOfSecond: 2018-10-25T23:12:31.123+02:00[Europe/Paris]  
ZonedDateTime after alter nanoOfSecond: 2018-10-25T23:31.439990+02:00[Europe/Paris] 

参考资料: https://docs.oracle.com/javase/10/docs/api/java/time/ZonedDateTime.html#withNano(int)

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程