如何使用LocalDateTime解析/格式化日期? (Java 8) [英] How to parse/format dates with LocalDateTime? (Java 8)
问题描述
我有日期和时间作为字符串(例如 2014-04-08 12:30
)。如何获取 LocalDateTime
来自给定字符串的实例?
完成使用 LocalDateTime
对象:如何将 LocalDateTime
实例转换成与上述格式相同的字符串?
解析日期和时间
创建一个 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);
格式化日期和时间
要创建一个 LocalDateTime
对象的格式化字符串,您可以使用 format()
方法。 / p>
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
。
parse()
和 format()
方法可用于所有日期/时间相关对象(例如 LocalDate
或 ZonedDateTime
)
Java 8 added a new API for working with dates and times (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?
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?
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.
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.
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"
.
The parse()
and format()
methods are available for all date/time related objects (e.g. LocalDate
or ZonedDateTime
)
这篇关于如何使用LocalDateTime解析/格式化日期? (Java 8)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!