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


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。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。