Java Period getYears()方法及示例

来源:这里教程网 时间:2026-02-17 21:05:40 作者:

Java Period getYears()方法及示例

Java中Period的getYears()方法是用来获取这个周期的年数的,它被使用。

注意: 15个月不等于1年零3个月。

语法

public List getYears()

参数: 该方法不接受任何参数。

返回: 该方法返回当前周期的年数。

下面的程序说明了上述方法。

程序1 :

// Java code to show the function getYears()// to get the number of years in the periodimport java.time.Period;import java.time.temporal.ChronoUnit;  public class PeriodDemo {      // Function to get the number of years    static void getNumberOfDays(int year, int months, int days)    {        Period period = Period.of(year, months, days);        System.out.println(period.getYears());    }      // Driver Code    public static void main(String[] args)    {          int year = 12;        int months = 3;        int days = 31;          getNumberOfDays(year, months, days);    }}

输出:

12

程序2 :

// Java code to show the function getYears()// to get the number of years in the periodimport java.time.Period;import java.time.temporal.ChronoUnit;  public class PeriodDemo {      // Function to get the number of years    static void getNumberOfDays(int year, int months, int days)    {        Period period = Period.of(year, months, days);        System.out.println(period.getYears());    }      // Driver Code    public static void main(String[] args)    {          int year = -12;        int months = 3;        int days = 31;          getNumberOfDays(year, months, days);    }}

输出:

-12

参考资料 : https://docs.oracle.com/javase/8/docs/api/java/time/Period.html#getYears-

相关推荐