因为您似乎对如何从您的ZonedDateTime
中获取日期感到困惑,所以我想补充一下Claudiu Guja的好而正确的答案。
ZoneId z = ZoneId.of("Africa/Nairobi");
ZonedDateTime zdt = ZonedDateTime.now(z);
System.out.println("Date " + zdt.toLocalDate());
System.out.println("Year " + zdt.getYear());
System.out.println("Month " + zdt.getMonth());
System.out.println("Day of month " + zdt.getDayOfMonth());
这仅仅打印出:
Date 2018-03-19
Year 2018
Month MARCH
Day of month 19
请查阅文档以获取更多方法,包括
getMonthValue
以获取月份的数字(1到12)。我在底部提供了链接。因为
ZonedDateTime
类有一个
now
方法,所以您不需要先使用
Instant.now()
。
如果您想要一个老式的
java.util.Date
对象 - 首先的答案是:不要这样做。您已经在使用现代API,这更易于使用。仅当您需要一个
Date
用于一些您无法更改或暂时不想更改的遗留API时,请获取
Instant
并将其转换:
Instant instant = Instant.now();
Date oldfashionedDateObject = Date.from(instant);
System.out.println("Old-fashioned java.util.Date " + oldfashionedDateObject);
这样打印出来:
Old-fashioned java.util.Date Mon Mar 19 12:00:05 CET 2018
尽管字符串中显示为中欧时间
CET
,但日期对象
Date
并不包含时区(这一点让很多人困惑)。只有当我将
Date
对象附加到
String
上时,它的
toString
方法(隐式调用)才会获取JVM的时区设置,并用于生成
String
,而
Date
本身则不受影响。
在特定情况下,如果您只需要表示当前日期和时间的
Date
对象,那么除非您有非常特定的需求,否则不建议使用,代码非常简单:
Date oldfashionedDateObject = new Date();
结果与上面相同。
链接