Java ZonedDateTime now()方法及示例
在ZonedDateTime类中,根据传递给它的参数,有三种类型的now()方法。
now()
ZonedDateTime 类的 now() 方法用于从默认时区的系统时钟中获取当前日期时间。该方法将返回基于默认时区的系统时钟的ZonedDateTime,以获取当前日期时间。区域和偏移量将根据时钟中的时区来设置。
语法
public static ZonedDateTime now()
参数: 该方法不接受任何参数。
返回值: 该方法使用系统时钟返回当前日期时间。
以下程序说明了now()方法:
程序1 :
// Java program to demonstrate
// ZonedDateTime.now() method
import java.time.*;
public class GFG {
public static void main(String[] args)
{
// create an ZonedDateTime object
ZonedDateTime lt
= ZonedDateTime.now();
// print result
System.out.println("ZonedDateTime : "
+ lt);
}
}
输出。
ZonedDateTime : 2019-01-21T05:36:18.973Z[Etc/UTC]
now(Clock clock)
ZonedDateTime 类的 now(Clock clock) 方法用于返回基于作为参数传递的指定时钟的当前日期时间,区域和偏移量将根据时钟的时区来设置。
语法
public static ZonedDateTime now(Clock clock)
参数: 该方法接受 时钟 作为参数,它是要使用的时钟。
返回值: 该方法返回 当前日期时间。
以下程序说明了now()方法:
程序1 :
// Java program to demonstrate
// ZonedDateTime.now() method
import java.time.*;
public class GFG {
public static void main(String[] args)
{
// create a clock
Clock cl = Clock.systemUTC();
// create an ZonedDateTime object using now(Clock)
ZonedDateTime lt
= ZonedDateTime.now(cl);
// print result
System.out.println("ZonedDateTime : "
+ lt);
}
}
输出。
ZonedDateTime : 2019-01-21T05:36:25.966Z
now(ZoneId zone)
now(ZoneId zone) 方法是 ZonedDateTime 类的一个方法,用于从作为参数传递的指定时区的系统时钟中返回当前日期时间。偏移量将从指定的时区开始计算。
语法
public static ZonedDateTime now(ZoneId zone)
参数: 该方法接受 zone 作为参数,它是要使用的区域。
返回值: 该方法返回 当前日期时间。
以下程序说明了now()方法:
程序1 :
// Java program to demonstrate
// ZonedDateTime.now() method
import java.time.*;
public class GFG {
public static void main(String[] args)
{
// create a clock
ZoneId zid = ZoneId.of("Europe/Paris");
// create an ZonedDateTime object using now(zoneId)
ZonedDateTime lt
= ZonedDateTime.now(zid);
// print result
System.out.println("ZonedDateTime : "
+ lt);
}
}
输出。
ZonedDateTime : 2019-01-21T06:36:30.188+01:00[Europe/Paris]
参考文献:
https://docs.oracle.com/javase/10/docs/api/java/time/ZonedDateTime.html#now()
https://docs.oracle.com/javase/10/docs/api/java/time/ZonedDateTime.html#now(java.time.Clock)
https://docs.oracle.com/javase/10/docs/api/java/time/ZonedDateTime.html#now(java.time.ZoneId)