Java Instant now()方法及实例

来源:这里教程网 时间:2026-02-17 20:51:54 作者:

Java Instant now()方法及实例

在Instant类中,根据传递给它的参数,有两种类型的now()方法。

now()

Instant 类的 now() 方法用于从系统UTC时钟中获取当前的时刻。

语法

public static Instant now()

参数: 该方法不接受任何参数。

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

以下程序说明了now()方法:

程序1 :

// Java program to demonstrate// Instant.now() method  import java.time.*;  public class GFG {    public static void main(String[] args)    {          // create an Instant object        Instant lt            = Instant.now();          // print result        System.out.println("Instant : "                           + lt);    }}

输出:

Instant : 2019-01-21T05:47:26.853Z

now(Clock clock)

Instant 类的 now(Clock clock) 方法用于返回基于作为参数传递的指定时钟的当前时刻。

语法

public static Instant now(Clock clock)

参数: 该方法接受 时钟 作为参数,它是要使用的时钟。

返回值: 该方法返回 Instant

以下程序说明了now()方法:
程序1 :

// Java program to demonstrate// Instant.now() method  import java.time.*;  public class GFG {    public static void main(String[] args)    {          // create a clock        Clock cl = Clock.systemUTC();          // create an Instant object using now(Clock)        Instant lt            = Instant.now(cl);          // print result        System.out.println("Instant : "                           + lt);    }}

输出:

Instant : 2019-01-21T05:47:29.886Z

References:

https://docs.oracle.com/javase/10/docs/api/java/time/Instant.html#now()
https://docs.oracle.com/javase/10/docs/api/java/time/Instant.html#now(java.time.Clock)

相关推荐