📜  Java中的 LocalDate minusDays() 方法及示例

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

Java中的 LocalDate minusDays() 方法及示例

Java中LocalDate类的minusDays()方法用于从这个 LocalDate 中减去指定的天数,并返回一个 LocalDate 的副本。例如,2019-01-01 减去一天将得到 2018-12-31。此实例是不可变的,不受此方法调用的影响。

句法:

public LocalDate minusDays(long daysToSubtract)

参数:此方法接受单个参数daysToSubtract ,它表示要减去的天数,可能为负数。

返回值:此方法返回基于此日期减去天数的LocalDate ,不为空。

异常:如果结果超出支持的日期范围,此方法将引发DateTimeException

下面的程序说明了 minusDays() 方法:
方案一:

// Java program to demonstrate
// LocalDate.minusDays() method
  
import java.time.*;
  
public class GFG {
    public static void main(String[] args)
    {
  
        // create a LocalDate object
        LocalDate date
            = LocalDate.parse("2018-11-13");
  
        // print instance
        System.out.println("LocalDate before"
                           + " subtracting days: " + date);
  
        // subtract 17 days
        LocalDate returnvalue
            = date.minusDays(17);
  
        // print result
        System.out.println("LocalDate after "
                           + " subtracting days: " + returnvalue);
    }
}
输出:
LocalDate before subtracting days: 2018-11-13
LocalDate after  subtracting days: 2018-10-27

方案二:

// Java program to demonstrate
// LocalDate.minusDays() method
  
import java.time.*;
  
public class GFG {
    public static void main(String[] args)
    {
  
        // create a LocalDate object
        LocalDate date
            = LocalDate.parse("2018-12-24");
  
        // print instance
        System.out.println("LocalDate before"
                           + " subtracting days: " + date);
  
        // subtract -15 days
        LocalDate returnvalue
            = date.minusDays(-15);
  
        // print result
        System.out.println("LocalDate after "
                           + " subtracting days: " + returnvalue);
    }
}
输出:
LocalDate before subtracting days: 2018-12-24
LocalDate after  subtracting days: 2019-01-08

参考:
https://docs.oracle.com/javase/10/docs/api/java Java)