如何使用 LocalDateTime 解析/格式化日期?(Java 8)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22463062/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to parse/format dates with LocalDateTime? (Java 8)
提问by micha
Java 8 added a new java.timeAPI for working with dates and times (JSR 310).
Java 8 添加了一个新的java.timeAPI 来处理日期和时间 ( JSR 310)。
I have date and time as string (e.g. "2014-04-08 12:30"
). How can I obtain a LocalDateTime
instance from the given string?
我将日期和时间作为字符串(例如"2014-04-08 12:30"
)。如何LocalDateTime
从给定的字符串中获取实例?
After I finished working with the LocalDateTime
object: How can I then convert the LocalDateTime
instance back to a string with the same format as shown above?
处理完LocalDateTime
对象后:如何将LocalDateTime
实例转换回与上述格式相同的字符串?
采纳答案by micha
Parsing date and time
解析日期和时间
To create a LocalDateTime
object from a string you can use the static LocalDateTime.parse()
method. It takes a string and a DateTimeFormatter
as parameter. The DateTimeFormatter
is used to specify the date/time pattern.
要从LocalDateTime
字符串创建对象,您可以使用静态LocalDateTime.parse()
方法。它接受一个字符串和一个DateTimeFormatter
作为参数。所述DateTimeFormatter
用于指定的日期/时间模式。
String str = "1986-04-08 12:30";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");
LocalDateTime dateTime = LocalDateTime.parse(str, formatter);
Formatting date and time
格式化日期和时间
To create a formatted string out a LocalDateTime
object you can use the format()
method.
要从LocalDateTime
对象中创建格式化字符串,您可以使用该format()
方法。
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");
LocalDateTime dateTime = LocalDateTime.of(1986, Month.APRIL, 8, 12, 30);
String formattedDateTime = dateTime.format(formatter); // "1986-04-08 12:30"
Note that there are some commonly used date/time formats predefined as constants in DateTimeFormatter
. For example: Using DateTimeFormatter.ISO_DATE_TIME
to format the LocalDateTime
instance from above would result in the string "1986-04-08T12:30:00"
.
请注意,有一些常用的日期/时间格式预定义为DateTimeFormatter
. 例如:使用从上面DateTimeFormatter.ISO_DATE_TIME
格式化LocalDateTime
实例将导致字符串"1986-04-08T12:30:00"
.
The parse()
and format()
methods are available for all date/time related objects (e.g. LocalDate
or ZonedDateTime
)
该parse()
和format()
方法可用于所有日期/时间相关的对象(例如LocalDate
或ZonedDateTime
)
回答by Sufiyan Ghori
You can also use LocalDate.parse()
or LocalDateTime.parse()
on a String
without providing it with a pattern, if the String
is in ISO-8601 format.
如果是ISO-8601 格式,您也可以在不提供模式的情况下使用LocalDate.parse()
或。LocalDateTime.parse()
String
String
for example,
例如,
String strDate = "2015-08-04";
LocalDate aLD = LocalDate.parse(strDate);
System.out.println("Date: " + aLD);
String strDatewithTime = "2015-08-04T10:11:30";
LocalDateTime aLDT = LocalDateTime.parse(strDatewithTime);
System.out.println("Date with Time: " + aLDT);
Output,
输出,
Date: 2015-08-04
Date with Time: 2015-08-04T10:11:30
and use DateTimeFormatter
only if you have to deal with other date patterns.
并且DateTimeFormatter
仅在您必须处理其他日期模式时使用。
For instance, in the following example, dd MMM uuuurepresents the day of the month (two digits), three letters of the name of the month (Jan, Feb, Mar,...), and a four-digit year:
例如,在下面的示例中,dd MMM uuuu表示月份中的第几天(两位数)、月份名称的三个字母(Jan、Feb、Mar、...)和一个四位数的年份:
DateTimeFormatter dTF = DateTimeFormatter.ofPattern("dd MMM uuuu");
String anotherDate = "04 Aug 2015";
LocalDate lds = LocalDate.parse(anotherDate, dTF);
System.out.println(anotherDate + " parses to " + lds);
Output
输出
04 Aug 2015 parses to 2015-08-04
also remember that the DateTimeFormatter
object is bidirectional; it can both parse input and format output.
还要记住DateTimeFormatter
对象是双向的;它既可以解析输入也可以格式化输出。
String strDate = "2015-08-04";
LocalDate aLD = LocalDate.parse(strDate);
DateTimeFormatter dTF = DateTimeFormatter.ofPattern("dd MMM uuuu");
System.out.println(aLD + " formats as " + dTF.format(aLD));
Output
输出
2015-08-04 formats as 04 Aug 2015
(see complete list of Patterns for Formatting and Parsing DateFormatter)
(请参阅格式化和解析 DateFormatter 的模式的完整列表)
Symbol Meaning Presentation Examples
------ ------- ------------ -------
G era text AD; Anno Domini; A
u year year 2004; 04
y year-of-era year 2004; 04
D day-of-year number 189
M/L month-of-year number/text 7; 07; Jul; July; J
d day-of-month number 10
Q/q quarter-of-year number/text 3; 03; Q3; 3rd quarter
Y week-based-year year 1996; 96
w week-of-week-based-year number 27
W week-of-month number 4
E day-of-week text Tue; Tuesday; T
e/c localized day-of-week number/text 2; 02; Tue; Tuesday; T
F week-of-month number 3
a am-pm-of-day text PM
h clock-hour-of-am-pm (1-12) number 12
K hour-of-am-pm (0-11) number 0
k clock-hour-of-am-pm (1-24) number 0
H hour-of-day (0-23) number 0
m minute-of-hour number 30
s second-of-minute number 55
S fraction-of-second fraction 978
A milli-of-day number 1234
n nano-of-second number 987654321
N nano-of-day number 1234000000
V time-zone ID zone-id America/Los_Angeles; Z; -08:30
z time-zone name zone-name Pacific Standard Time; PST
O localized zone-offset offset-O GMT+8; GMT+08:00; UTC-08:00;
X zone-offset 'Z' for zero offset-X Z; -08; -0830; -08:30; -083015; -08:30:15;
x zone-offset offset-x +0000; -08; -0830; -08:30; -083015; -08:30:15;
Z zone-offset offset-Z +0000; -0800; -08:00;
p pad next pad modifier 1
' escape for text delimiter
'' single quote literal '
[ optional section start
] optional section end
# reserved for future use
{ reserved for future use
} reserved for future use
回答by Marcio Jasinski
Both answers above explain very well the question regarding string patterns. However, just in case you are working with ISO 8601there is no need to apply DateTimeFormatter
since LocalDateTime is already prepared for it:
上面的两个答案都很好地解释了有关字符串模式的问题。但是,如果您正在使用ISO 8601,则无需申请,DateTimeFormatter
因为 LocalDateTime 已经为它做好了准备:
Convert LocalDateTime to Time Zone ISO8601 String
将 LocalDateTime 转换为时区 ISO8601 字符串
LocalDateTime ldt = LocalDateTime.now();
ZonedDateTime zdt = ldt.atZone(ZoneOffset.UTC); //you might use a different zone
String iso8601 = zdt.toString();
Convert from ISO8601 String back to a LocalDateTime
从 ISO8601 字符串转换回 LocalDateTime
String iso8601 = "2016-02-14T18:32:04.150Z";
ZonedDateTime zdt = ZonedDateTime.parse(iso8601);
LocalDateTime ldt = zdt.toLocalDateTime();
回答by Ondra ?i?ka
Parsing a string with date and time into a particular point in time (Java calls it an "Instant
") is quite complicated. Java has been tackling this in several iterations. The latest one, java.time
and java.time.chrono
, covers almost all needs (except Time Dilation:) ).
将带有日期和时间的字符串解析为特定时间点(Java 称之为“ Instant
”)非常复杂。Java 已经在多次迭代中解决了这个问题。最新的,java.time
和java.time.chrono
,几乎涵盖了所有需求(除了时间膨胀:))。
However, that complexity brings a lot of confusion.
然而,这种复杂性带来了很多混乱。
The key to understand date parsing is:
理解日期解析的关键是:
Why does Java have so many ways to parse a date
为什么 Java 有这么多方法来解析日期
- There are several systems to measure a time. For instance, the historical Japanese calendars were derived from the time ranges of the reign of the respective emperor or dynasty. Then there is e.g. UNIX timestamp. Fortunately, the whole (business) world managed to use the same.
- Historically, the systems were being switched from/to, for various reasons. E.g. from Julian calendar to Gregorian calendar in 1582. So 'western' dates before that need to be treated differently.
- And of course the change did not happen at once. Because the calendar came from the headquarteds of some religion and other parts of Europe believed in other dieties, for instance Germany did not switch until the year 1700.
- 有几种系统可以测量时间。例如,历史上的日本历法是从各自的天皇或王朝统治的时间范围派生出来的。然后是例如 UNIX 时间戳。幸运的是,整个(商业)世界都设法使用了相同的方法。
- 从历史上看,由于各种原因,系统正在相互切换。例如,从儒略历到 1582 年的格里高利历。所以在此之前的“西方”日期需要区别对待。
- 当然,这种变化并不是一下子发生的。因为日历来自某些宗教的总部,而欧洲其他地区则相信其他宗教,例如德国直到 1700 年才转换。
...and why is the LocalDateTime
, ZonedDateTime
et al. so complicated
...以及为什么LocalDateTime
,ZonedDateTime
等。这么复杂
There are time zones. A time zone is basically a "stripe"*[1]of the Earth's surface whose authorities follow the same rules of when does it have which time offset. This includes summer time rules.
The time zones change over time for various areas, mostly based on who conquers whom. And one time zone's rules change over timeas well.There are time offsets. That is not the same as time zones, because a time zone may be e.g. "Prague", but that has summer time offset and winter time offset.
If you get a timestamp with a time zone, the offset may vary, depending on what part of the year it is in. During the leap hour, the timestamp may mean 2 different times, so without additional information, it can't be reliably converted.
Note: By timestampI mean "a string that contains a date and/or time, optionally with a time zone and/or time offset."Several time zones may share the same time offset for certain periods. For instance, GMT/UTC time zone is the same as "London" time zone when the summer time offset is not in effect.
有时区。时区基本上是地球表面的“条纹” *[1],其权威遵循相同的规则,即何时具有哪个时间偏移。这包括夏令时规则。
各个地区的时区随着时间的推移而变化,主要取决于谁征服了谁。一个时区的规则也会随着时间而改变。有时间偏移。这与时区不同,因为时区可能是例如“布拉格”,但具有夏季时间偏移和冬季时间偏移。
如果您获得带时区的时间戳,则偏移量可能会有所不同,具体取决于它所在年份的哪个部分。在闰小时,时间戳可能表示 2 个不同的时间,因此如果没有附加信息,则无法可靠转换。
注意:时间戳我的意思是“一个包含日期和/或时间的字符串,可选时区和/或时间偏移。”多个时区可能在某些时期共享相同的时间偏移。例如,当夏令时偏移无效时,GMT/UTC 时区与“伦敦”时区相同。
To make it a bit more complicated (but that's not too important for your use case) :
为了使它更复杂一点(但这对您的用例来说不太重要):
- The scientists observe Earth's dynamic, which changes over time; based on that, they add seconds at the end of individual years. (So
2040-12-31 24:00:00
may be a valid date-time.) This needs regular updates of the metadata that systems use to have the date conversions right. E.g. on Linux, you get regular updates to the Java packages including these new data. The updates do not always keep the previous behavior for both historical and future timestamps. So it may happen that parsing of the two timestamps around some time zone's change comparing them may give different resultswhen running on different versions of the software. That also applies to comparing between the affected time zone and other time zone.
Should this cause a bug in your software, consider using some timestamp that does not have such complicated rules, like UNIX timestamp.
Because of 7, for the future dates, we can't convert dates exactly with certainty. So, for instance, current parsing of
8524-02-17 12:00:00
may be off a couple of seconds from the future parsing.
- 科学家们观察地球的动态,随着时间的推移而变化;在此基础上,他们在个别年份结束时增加秒数。(所以
2040-12-31 24:00:00
可能是一个有效的日期时间。)这需要定期更新系统用来正确转换日期的元数据。例如,在 Linux 上,您会定期更新 Java 包,包括这些新数据。 更新并不总是保留历史和未来时间戳的先前行为。因此,当在不同版本的软件上运行时,围绕某个时区的变化解析两个时间戳可能会产生不同的结果。这也适用于受影响的时区和其他时区之间的比较。
如果这会导致您的软件出现错误,请考虑使用一些没有如此复杂规则的时间戳,例如UNIX timestamp。
由于 7,对于未来的日期,我们无法准确地转换日期。因此,例如,当前的解析
8524-02-17 12:00:00
可能与未来的解析相距几秒钟。
JDK's APIs for this evolved with the contemporary needs
JDK 的 API 随当代需求而发展
- The early Java releases had just
java.util.Date
which had a bit naive approach, assuming that there's just the year, month, day, and time. This quickly did not suffice. - Also, the needs of the databases were different, so quite early,
java.sql.Date
was introduced, with it's own limitations. - Because neither covered different calendars and time zones well, the
Calendar
API was introduced. - This still did not cover the complexity of the time zones. And yet, the mix of the above APIs was really a pain to work with. So as Java developers started working on global web applications, libraries that targeted most use cases, like JodaTime, got quickly popular. JodaTime was the de-facto standard for about a decade.
- But the JDK did not integrate with JodaTime, so working with it was a bit cumbersome. So, after a very long discussion on how to approach the matter, JSR-310was created mainly based on JodaTime.
- 早期的 Java 版本只是
java.util.Date
采用了一种有点幼稚的方法,假设只有年、月、日和时间。这很快还不够。 - 此外,数据库的需求是不同的,所以很早就
java.sql.Date
引入了,有其自身的局限性。 - 因为两者都不能很好地涵盖不同的日历和时区,所以
Calendar
引入了API。 - 这仍然没有涵盖时区的复杂性。然而,上述 API 的混合使用起来确实很痛苦。因此,随着 Java 开发人员开始开发全球 Web 应用程序,针对大多数用例的库(如 JodaTime)迅速流行起来。JodaTime 是事实上的标准大约十年。
- 但是 JDK 没有与 JodaTime 集成,所以使用它有点麻烦。因此,在对如何处理这个问题进行了很长时间的讨论之后,JSR-310主要是基于 JodaTime创建的。
How to deal with it in Java's java.time
如何在 Java 中处理它 java.time
Determine what type to parse a timestamp to
确定将时间戳解析为哪种类型
When you are consuming a timestamp string, you need to know what information it contains. This is the crucial point.If you don't get this right, you end up with a cryptic exceptions like "Can't create Instant" or "Zone offset missing" or "unknown zone id" etc.
当您使用时间戳字符串时,您需要知道它包含哪些信息。这是关键点。如果你没有做对,你最终会得到一个神秘的异常,比如“无法创建即时”或“区域偏移丢失”或“未知区域 ID”等。
- Unable to obtain OffsetDateTime from TemporalAccessor
- Unable to obtain ZonedDateTime from TemporalAccessor
- Unable to obtain LocalDateTime from TemporalAccessor
- Unable to obtain Instant from TemporalAccessor
- 无法从 TemporalAccessor 获取 OffsetDateTime
- 无法从 TemporalAccessor 获取 ZonedDateTime
- 无法从 TemporalAccessor 获取 LocalDateTime
- 无法从 TemporalAccessor 获取 Instant
Does it contain the date and the time?
它包含日期和时间吗?
Does it have a time offset?
A time offset is the+hh:mm
part. Sometimes,+00:00
may be substituted withZ
as 'Zulu time',UTC
as Universal Time Coordinated, orGMT
as Greenwich Mean Time. These also set the time zone.
For these timestamps, you useOffsetDateTime
.Does it have a time zone?
For these timestamps, you useZonedDateTime
.
Zone is specified either by- name ("Prague", "Pacific Standard Time", "PST"), or
- "zone ID" ("America/Los_Angeles", "Europe/London"), represented by java.time.ZoneId.
The list of time zones is compiled by a "TZ database", backed by ICAAN.
According to
ZoneId
's javadoc, The zone id's can also somehow be specified asZ
and offset. I'm not sure how this maps to real zones. If the timestamp, which only has a TZ, falls into a leap hour of time offset change, then it is ambiguous, and the interpretation is subject ofResolverStyle
, see below.If it has neither, then the missing context is assumed or neglected. And the consumer has to decide. So it needs to be parsed as
LocalDateTime
and converted toOffsetDateTime
by adding the missing info:- You can assumethat it is a UTC time. Add the UTC offset of 0 hours.
- You can assumethat it is a time of the place where the conversion is happening. Convert it by adding the system's time zone.
- You can neglectand just use it as is. That is useful e.g. to compare or substract two times (see
Duration
), or when you don't know and it doesn't really matter (e.g. local bus schedule).
它有时间偏移吗?
时间偏移是+hh:mm
一部分。有时,+00:00
可以替换Z
为“祖鲁时间”、UTC
协调世界时或GMT
格林威治标准时间。这些也设置了时区。
对于这些时间戳,您使用OffsetDateTime
.它有时区吗?
对于这些时间戳,您使用ZonedDateTime
.
区域由- 名称(“布拉格”、“太平洋标准时间”、“太平洋标准时间”),或
- “区域 ID”(“America/Los_Angeles”、“Europe/London”),由java.time.ZoneId表示。
时区列表由 ICAAN 支持的“TZ 数据库”编制。
根据
ZoneId
's javadoc,区域 ID 也可以以某种方式指定为Z
和偏移量。我不确定这如何映射到真实区域。如果时间戳,只有一个TZ,落入时间偏移变化的闰小时,那么它是有歧义的,解释是主题ResolverStyle
,见下文。如果两者都没有,则假定或忽略缺失的上下文。而消费者必须做出决定。因此需要通过添加缺少的信息将其解析为
LocalDateTime
并转换为OffsetDateTime
:- 您可以假设它是 UTC 时间。添加 0 小时的 UTC 偏移量。
- 您可以假设这是发生转换的地点的时间。通过添加系统的时区来转换它。
- 您可以忽略并按原样使用它。这很有用,例如比较或减去两次(请参阅 参考资料
Duration
),或者当您不知道并且并不重要时(例如当地巴士时刻表)。
Partial time information
部分时间信息
- Based on what the timestamp contains, you can take
LocalDate
,LocalTime
,OffsetTime
,MonthDay
,Year
, orYearMonth
out of it.
- 基于什么样的时间戳包含,你可以采取
LocalDate
,LocalTime
,OffsetTime
,MonthDay
,Year
,或YearMonth
出来。
If you have the full information, you can get a java.time.Instant
. This is also internally used to convert between OffsetDateTime
and ZonedDateTime
.
如果你有完整的信息,你可以得到一个java.time.Instant
. 这也在内部用于在OffsetDateTime
和之间进行转换ZonedDateTime
。
Figure out how to parse it
弄清楚如何解析它
There is an extensive documentation on DateTimeFormatter
which can both parse a timestamp string and format to string.
有大量文档DateTimeFormatter
可以解析时间戳字符串和格式到字符串。
The pre-created DateTimeFormatter
sshould cover moreless all standard timestamp formats. For instance, ISO_INSTANT
can parse 2011-12-03T10:15:30.123457Z
.
在预先创建DateTimeFormatter
小号应涵盖所有收起标准时间戳的格式。例如,ISO_INSTANT
可以解析2011-12-03T10:15:30.123457Z
.
If you have some special format, then you can create your own DateTimeFormatter(which is also a parser).
如果你有一些特殊的格式,那么你可以创建你自己的 DateTimeFormatter(它也是一个解析器)。
private static final DateTimeFormatter TIMESTAMP_PARSER = new DateTimeFormatterBuilder()
.parseCaseInsensitive()
.append(DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SX"))
.toFormatter();
I recommend to look at the source code of DateTimeFormatter
and get inspired on how to build one using DateTimeFormatterBuilder
. While you're there, also have a look at ResolverStyle
which controls whether the parser is LENIENT, SMART or STRICT for the formats and ambiguous information.
我建议查看 的源代码DateTimeFormatter
并获得有关如何使用DateTimeFormatterBuilder
. 当您在那里时,还可以查看ResolverStyle
控制解析器是 LENIENT、SMART 还是 STRICT 的格式和模糊信息。
TemporalAccessor
时间访问器
Now, the frequent mistake is to go into the complexity of TemporalAccessor
. This comes from how the developers were used to work with SimpleDateFormatter.parse(String)
. Right, DateTimeFormatter.parse("...")
gives you TemporalAccessor
.
现在,经常犯的错误是进入TemporalAccessor
. 这来自于开发人员过去如何使用SimpleDateFormatter.parse(String)
. 对,DateTimeFormatter.parse("...")
给你TemporalAccessor
。
// No need for this!
TemporalAccessor ta = TIMESTAMP_PARSER.parse("2011-... etc");
But, equiped with the knowledge from the previous section, you can conveniently parse into the type you need:
但是,有了上一节的知识,您可以方便地解析为您需要的类型:
OffsetDateTime myTimestamp = OffsetDateTime.parse("2011-12-03T10:15:30.123457Z", TIMESTAMP_PARSER);
You do not actually need to the DateTimeFormatter
either. The types you want to parse have the parse(String)
methods.
您实际上也不需要DateTimeFormatter
。您要解析的类型具有parse(String)
方法。
OffsetDateTime myTimestamp = OffsetDateTime.parse("2011-12-03T10:15:30.123457Z");
Regarding TemporalAccessor
, you can use it if you have a vague idea of what information there is in the string, and want to decide at runtime.
关于TemporalAccessor
,如果您对字符串中包含哪些信息有一个模糊的概念,并且想在运行时做出决定,则可以使用它。
I hope I shed some light of understanding onto your soul :)
我希望我能对你的灵魂有所了解:)
Note: There's a backport of java.time
to Java 6 and 7: ThreeTen-Backport. For Android it has ThreeTenABP.
注意:java.time
Java 6 和 7有一个向后移植:ThreeTen-Backport。对于 Android,它有ThreeTenABP。
[1]Not just that they are not stripes, but there also some weird extremes. For instance, some neighboring pacific islandshave +14:00 and -11:00 time zones. That means, that while on one island, there is 1st May 3 PM, on another island not so far, it is still 30 April 12 PM (if I counted correctly :) )
[1]不仅它们不是条纹,而且还有一些奇怪的极端。例如,一些邻近的太平洋岛屿有 +14:00 和 -11:00 时区。这意味着,虽然在一个岛上,是 5 月 1 日下午 3 点,但在另一个岛上,它仍然是 4 月 30 日下午 12 点(如果我算对了:))
回答by flowgrad
I found the it wonderful to cover multiple variants of date time format like this:
我发现像这样涵盖日期时间格式的多种变体真是太好了:
final DateTimeFormatterBuilder dtfb = new DateTimeFormatterBuilder();
dtfb.appendOptional(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSSSSSSSS"))
.appendOptional(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSSSSSSS"))
.appendOptional(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSSSSSS"))
.appendOptional(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSSSSS"))
.appendOptional(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSSSS"))
.appendOptional(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSSS"))
.appendOptional(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS"))
.appendOptional(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SS"))
.appendOptional(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.S"))
.parseDefaulting(ChronoField.HOUR_OF_DAY, 0)
.parseDefaulting(ChronoField.MINUTE_OF_HOUR, 0)
.parseDefaulting(ChronoField.SECOND_OF_MINUTE, 0);
回答by Santhosh Hirekerur
GET CURRENT UTC TIME IN REQUIRED FORMAT
以所需格式获取当前 UTC 时间
// Current UTC time
OffsetDateTime utc = OffsetDateTime.now(ZoneOffset.UTC);
// GET LocalDateTime
LocalDateTime localDateTime = utc.toLocalDateTime();
System.out.println("*************" + localDateTime);
// formated UTC time
DateTimeFormatter dTF = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");
System.out.println(" formats as " + dTF.format(localDateTime));
//GET UTC time for current date
Date now= new Date();
LocalDateTime utcDateTimeForCurrentDateTime = Instant.ofEpochMilli(now.getTime()).atZone(ZoneId.of("UTC")).toLocalDateTime();
DateTimeFormatter dTF2 = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");
System.out.println(" formats as " + dTF2.format(utcDateTimeForCurrentDateTime));