📜  带有示例的Java中的 YearMonth now(zone)

📅  最后修改于: 2022-05-13 01:55:18.397000             🧑  作者: Mango

带有示例的Java中的 YearMonth now(zone)

Java中YearMonth类的now(ZoneId zone)方法用于从指定时区的系统时钟中获取当前的年月。
句法:

public static YearMonth now(ZoneId zone)

参数:此方法接受monthsToAdd作为参数,表示要使用的区域ID。

返回值:该方法使用系统时钟返回当前的年月。

下面的程序说明了Java中 YearMonth 的 now(ZoneId zone) 方法:

方案一:

// 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

方案二:

// 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: Java Java)