如何使用 LocalDateTime 解析/格式化日期?(Java 8) [英] How to parse/format dates with LocalDateTime? (Java 8)
问题描述
Java 8 添加了一个新的java.time 用于处理日期和时间的 API (JSR 310).
Java 8 added a new java.time API for working with dates and times (JSR 310).
我将日期和时间作为字符串(例如 "2014-04-08 12:30"
).我如何获得 LocalDateTime
给定字符串中的实例?
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?
在我使用完 LocalDateTime
对象后:我怎样才能将 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.parse()
方法.它需要一个字符串和一个 DateTimeFormatter
作为参数.DateTimeFormatter
用于指定日期/时间模式.
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.
String str = "1986-04-08 12:30";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");
LocalDateTime dateTime = LocalDateTime.parse(str, formatter);
格式化日期和时间
要从 LocalDateTime
对象中创建格式化字符串,您可以使用 format()
方法.
To create a formatted string out a LocalDateTime
object you can use the format()
method.
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"
请注意,在DateTimeFormatter
中有一些常用的日期/时间格式预定义为常量.例如:使用 DateTimeFormatter.ISO_DATE_TIME
从上面格式化 LocalDateTime
实例将导致字符串 "1986-04-08T12:30:00"
.
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"
.
parse()
和 format()
方法可用于所有与日期/时间相关的对象(例如 LocalDate
或 ZonedDateTime
)
The parse()
and format()
methods are available for all date/time related objects (e.g. LocalDate
or ZonedDateTime
)
这篇关于如何使用 LocalDateTime 解析/格式化日期?(Java 8)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!