📜  Java中的 YearMonth now(clock) 方法和示例

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

Java中的 YearMonth now(clock) 方法和示例

Java中YearMonth类的now(Clock clock)方法用于从指定的时钟获取当前的年月。
句法:

public static YearMonth
         now(Clock clock)

参数:此方法接受时钟作为参数,表示要使用的时钟。

返回值:该方法返回当前的year-month

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

方案一:

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

方案二:

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

参考资料: https: Java Java.time.Clock)