在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)方法用于根据作为参数传递的指定时钟返回当前日期时间。zone和offset将根据时钟中的时区进行设置。
用法:
public static ZonedDateTime now(Clock 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)
ZonedDateTime类的now(ZoneId zone)方法用于从作为参数传递的指定时区中的系统时钟返回当前日期时间。指定时区可以避免依赖默认时区。偏移量将从指定的时区计算得出。
用法:
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]