java实现 plusin,Java Period plusYears()用法及代码示例

Java中Period类的plusYears()方法用于将给定的年份添加到此期间。此功能仅在YEARS起作用,并且不影响MONTH和DAYS。

用法:

public Period plusYears(long yearsToAdd)

参数:此方法接受单个参数yearsToAdd,这是要添加到期间的年数。

返回值:此方法基于输入中提供的期间加上指定的年数来返回“期间”。不能为空。

异常:它引发ArithmeticException。如果发生数字溢出,则会捕获此异常。

以下示例程序旨在说明上述方法:

示例1:

// Java code to show the function plusYears()

// to add the number of years from given periods

import java.time.Period;

import java.time.temporal.ChronoUnit;

public class PeriodClass {

// Function to add years to given period

static void addYears(Period p1, int yearstoAdd)

{

System.out.println(p1.plusYears(yearstoAdd));

}

// Driver Code

public static void main(String[] args)

{

// Defining first period

int year = 4;

int months = 11;

int days = 10;

Period p1 = Period.of(year, months, days);

int yearstoAdd = 8;

addYears(p1, yearstoAdd);

}

}

输出:

P12Y11M10D

程序2:期间可以为负。

// Java code to show the function plusYears()

// to add the number of years to given periods

import java.time.Period;

import java.time.temporal.ChronoUnit;

public class PeriodClass {

// Function to add years to given periods

static void addYears(Period p1, int yearstoAdd)

{

System.out.println(p1.plusYears(yearstoAdd));

}

// Driver Code

public static void main(String[] args)

{

// Defining first period

int year = -4;

int months = -11;

int days = 0;

Period p1 = Period.of(year, months, days);

int yearstoAdd = 8;

addYears(p1, yearstoAdd);

}

}

输出:

P4Y-11M

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值