java datetime now_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)方法用于根据作为参数传递的指定时钟返回当前日期时间。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]

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值