📌  相关文章
📜  Java中的持续时间减(持续时间)方法与示例

📅  最后修改于: 2022-05-13 01:54:21.646000             🧑  作者: Mango

Java中的持续时间减(持续时间)方法与示例

Java.time 包Duration 类minus(Duration)方法用于获取该持续时间的不可变副本,减去指定的持续时间,作为参数传递。
句法:

public Duration minus(Duration duration)

参数:此方法接受参数持续时间,该参数是要减去的持续时间。它可以是正数或负数,但不能为空。
返回值:此方法返回一个持续时间,它是现有持续时间的不可变副本,其中减去了持续时间的参数量。
异常:如果发生数字溢出,此方法将引发ArithmeticException
下面的示例说明了 Duration.minus() 方法:
示例 1:

Java
// Java code to illustrate minus() method
 
import java.time.Duration;
 
public class GFG {
    public static void main(String[] args)
    {
 
        // Duration 1 using parse() method
        Duration duration1
            = Duration.parse("P2DT3H4M");
 
        // Duration 2 using ofHours() method
        Duration duration2
            = Duration.ofHours(5);
 
        // Get the duration subtracted
        // using minus() method
        System.out.println(duration1
                               .minus(duration2));
    }
}


Java
// Java code to illustrate minus() method
 
import java.time.Duration;
 
public class GFG {
    public static void main(String[] args)
    {
 
        // Duration 1 using parse() method
        Duration duration1
            = Duration.parse("P0DT0H4M");
 
        // Duration 2 using ofHours() method
        Duration duration2
            = Duration.ofDays(5);
 
        // Get the duration subtracted
        // using minus() method
        System.out.println(duration1
                               .minus(duration2));
    }
}


输出:
PT46H4M

示例 2:

Java

// Java code to illustrate minus() method
 
import java.time.Duration;
 
public class GFG {
    public static void main(String[] args)
    {
 
        // Duration 1 using parse() method
        Duration duration1
            = Duration.parse("P0DT0H4M");
 
        // Duration 2 using ofHours() method
        Duration duration2
            = Duration.ofDays(5);
 
        // Get the duration subtracted
        // using minus() method
        System.out.println(duration1
                               .minus(duration2));
    }
}
输出:
PT-119H-56M

参考: https://docs.oracle.com/javase/9/docs/api/ Java/time/Duration.html#minus-java.time.Duration-