Java ChronoPeriod negated()方法及示例

来源:这里教程网 时间:2026-02-17 20:41:15 作者:

Java ChronoPeriod negated()方法及示例

Java中 ChronoPeriod接口negated() 方法用于在否定了YEAR, MONTH, DAY中的所有元素后返回ChronoPeriod的一个新实例。

语法

ChronoPeriod negated()

参数: 该方法不接受任何参数。

返回值: 该方法在否定了周期的每个元素后返回一个新的ChronoPeriod实例。

异常: 它抛出一个 ArithmeticException。 如果发生数字溢出,这个异常将被捕获。

下面的程序说明了上述方法。

程序1 :

// Java code to show the function to negate all// elements of the period  import java.time.*;import java.time.chrono.*;import java.time.temporal.ChronoUnit;  public class ChronoPeriodClass {      // Function to negate given periods    static void toNegate(ChronoPeriod p1)    {          System.out.println(p1.negated());    }      // Driver Code    public static void main(String[] args)    {        // Defining period        int year = 4;        int months = 11;        int days = 10;        ChronoPeriod p1 = Period.of(year, months, days);          toNegate(p1);    }}

输出:

P-4Y-11M-10D

程序2 :

// Java code to show the function to negate all// elements of the period  import java.time.*;import java.time.chrono.*;import java.time.temporal.ChronoUnit;  public class ChronoPeriodClass {      // Function to negate given periods    static void toNegate(ChronoPeriod p1)    {          System.out.println(p1.negated());    }      // Driver Code    public static void main(String[] args)    {        // Defining period        int year = -4;        int months = -11;        int days = -10;        ChronoPeriod p1 = Period.of(year, months, days);          toNegate(p1);    }}

输出:

P4Y11M10D

参考资料 : https://docs.oracle.com/javase/9/docs/api/java/time/chrono/ChronoPeriod.html#negated-

相关推荐