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


Java YearMonth now(zone)用法及代碼示例

Java中YearMonth類的now(ZoneId zone)方法用於從指定時區的係統時鍾中獲取當前的year-month。句法:

public static YearMonth now(ZoneId zone)

參數:此方法接受monthsToAdd作為參數,代表要使用的區域ID。

返回值:此方法使用係統時鍾返回當前的year-month。



以下示例程序旨在說明Java中YearMonth的now(ZoneId zone)方法:

程序1:

// Java program to demonstrate 
// YearMonth.now(ZoneId zone) method 
  
import java.time.*; 
import java.time.temporal.*; 
  
public class GFG { 
    public static void main(String[] args) 
    { 
  
        // apply now(ZoneId zone) method 
        // of YearMonth class 
        YearMonth result 
            = YearMonth.now( 
                ZoneId.systemDefault()); 
  
        // print both year and month 
        System.out.println("YearMonth:"
                           + result); 
    } 
}
輸出:
YearMonth:2020-05

程序2:

// Java program to demonstrate 
// YearMonth.now(ZoneId zone) method 
  
import java.time.*; 
import java.time.temporal.*; 
  
public class GFG { 
    public static void main(String[] args) 
    { 
  
        // apply now(ZoneId zone) method 
        // of YearMonth class 
        YearMonth result 
            = YearMonth.now( 
                ZoneId.systemDefault()); 
  
        // print only year 
        System.out.println( 
            "Year:"
            + result.get( 
                  ChronoField.YEAR)); 
    } 
}
輸出:
Year:2020

程序3:

// Java program to demonstrate 
// YearMonth.now(ZoneId zone) method 
  
import java.time.*; 
import java.time.temporal.*; 
  
public class GFG { 
    public static void main(String[] args) 
    { 
  
        // apply now(ZoneId zone) method 
        // of YearMonth class 
        YearMonth result 
            = YearMonth.now( 
                ZoneId.systemDefault()); 
  
        // print only month 
        System.out.println( 
            "Month:"
            + result.get( 
                  ChronoField.MONTH_OF_YEAR)); 
    } 
}
輸出:
Month:5

參考文獻: https://docs.oracle.com/javase/10/docs/api/java/time/YearMonth.html#now(java.time.ZoneId)




相關用法


注:本文由純淨天空篩選整理自pp_pankaj大神的英文原創作品 YearMonth now(zone) in Java with Examples。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。