當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


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。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。