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

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

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

Java中LocalDate类的plusWeeks()方法用于在这个LocalDate中加上指定的周数,并返回一个LocalDate的副本。例如,2018-12-24加一周会得到2018-12-31。此实例是不可变的,不受此方法调用的影响。

句法:

public LocalDate plusWeeks(long weeksToAdd)

参数:此方法接受单个参数weekToAdd ,它表示要添加的周数,可能为负数。

返回值:此方法基于此日期返回一个LocalDate并添加周数,而不是 null。

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

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

方案一:

// Java program to demonstrate
// LocalDate.plusWeeks() 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"
                           + " adding weeks: " + date);
  
        // add 5 weeks
        LocalDate returnvalue
            = date.plusWeeks(5);
  
        // print result
        System.out.println("LocalDate after "
                           + " adding weeks: " + returnvalue);
    }
}

输出:

LocalDate before adding weeks: 2018-12-26
LocalDate after  adding weeks: 2019-01-30

方案二:

// Java program to demonstrate
// LocalDate.plusWeeks() 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"
                           + " adding weeks: " + date);
  
        // add -3 weeks
        LocalDate returnvalue
            = date.plusWeeks(-3);
  
        // print result
        System.out.println("LocalDate after "
                           + " adding weeks: " + returnvalue);
    }
}
输出:
LocalDate before adding weeks: 2018-12-24
LocalDate after  adding weeks: 2018-12-03

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