当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


Java ZonedDateTime minusYears()用法及代码示例


ZonedDateTime类的minusYears()方法用于从此ZonedDateTime中减去年数,并在减法后返回ZonedDateTime的副本。此方法在本地时间轴上操作,从本地日期时间中减去年份,再减去年份本地日期后使用区域ID获取偏移量,将-time转换回ZonedDateTime。当转换回ZonedDateTime时,如果本地日期时间重叠,则将尽可能保留偏移量,否则将使用较早的偏移量。此实例是不可变的,不受此方法调用的影响。

用法:

public ZonedDateTime minusYears(long years)

参数:此方法接受一个代表年份的单个参数,该年份代表要减去的年份,可以为负数。


返回值:此方法基于此日期时间并减去年份返回一个ZonedDateTime。

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

以下示例程序旨在说明minusYears()方法:
示例1:

// Java program to demonstrate 
// ZonedDateTime.minusYears() method 
  
import java.time.*; 
  
public class GFG { 
    public static void main(String[] args) 
    { 
  
        // create a ZonedDateTime object 
        ZonedDateTime zoneddatetime 
            = ZonedDateTime 
                  .parse( 
                      "2018-12-06T19:21:12.123+05:30[Asia/Calcutta]"); 
  
        // print instance 
        System.out.println("ZonedDateTime before"
                           + " subtracting years: "
                           + zoneddatetime); 
  
        // subtract 15 years 
        ZonedDateTime returnvalue 
            = zoneddatetime.minusYears(5); 
  
        // print result 
        System.out.println("ZonedDateTime after "
                           + "subtracting 15 years: "
                           + returnvalue); 
    } 
}
输出:

ZonedDateTime before subtracting years: 2018-12-06T19:21:12.123+05:30[Asia/Calcutta]
ZonedDateTime after subtracting 15 years: 2013-12-06T19:21:12.123+05:30[Asia/Calcutta]

示例2:

// Java program to demonstrate 
// ZonedDateTime.minusYears() method 
  
import java.time.*; 
  
public class GFG { 
    public static void main(String[] args) 
    { 
  
        // create a ZonedDateTime object 
        ZonedDateTime zoneddatetime 
            = ZonedDateTime.parse( 
                "2018-10-25T23:12:31.123+02:00[Europe/Paris]"); 
  
        // print instance 
        System.out.println("ZonedDateTime before"
                           + " subtracting years: "
                           + zoneddatetime); 
  
        // subtract 12 years 
        ZonedDateTime returnvalue 
            = zoneddatetime.minusYears(12); 
  
        // print result 
        System.out.println("ZonedDateTime after "
                           + "subtracting 12 years: "
                           + returnvalue); 
    } 
}
输出:

ZonedDateTime before subtracting years: 2018-10-25T23:12:31.123+02:00[Europe/Paris]
ZonedDateTime after subtracting 12 years: 2006-10-25T23:12:31.123+02:00[Europe/Paris]

参考: https://docs.oracle.com/javase/10/docs/api/java/time/ZonedDateTime.html#minusYears(long)



相关用法


注:本文由纯净天空筛选整理自AmanSingh2210大神的英文原创作品 ZonedDateTime minusYears() method in Java with Examples。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。