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

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

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

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

句法:

public LocalDate minusWeeks(long weeksToSubtract)

参数:此方法接受一个参数weeksToSubtract ,它表示要减去的周数,可能为负数。

返回值:此方法返回基于此日期减去周数的LocalDate ,而不是 null。

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

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

方案一:

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

方案二:

// Java program to demonstrate
// LocalDate.minusWeeks() 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 weeks: " + date);
  
        // subtract -13 weeks
        LocalDate returnvalue
            = date.minusWeeks(-13);
  
        // print result
        System.out.println("LocalDate after "
                           + " subtracting weeks: " + returnvalue);
    }
}
输出:
LocalDate before subtracting weeks: 2018-12-24
LocalDate after  subtracting weeks: 2019-03-25

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