Java 8 added a new java.time 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?
Best Answer
Parsing date and time
To create a
LocalDateTime
object from a string you can use the staticLocalDateTime.parse()
method. It takes a string and aDateTimeFormatter
as parameter. TheDateTimeFormatter
is used to specify the date/time pattern.Formatting date and time
To create a formatted string out a
LocalDateTime
object you can use theformat()
method.Note that there are some commonly used date/time formats predefined as constants in
DateTimeFormatter
. For example: UsingDateTimeFormatter.ISO_DATE_TIME
to format theLocalDateTime
instance from above would result in the string"1986-04-08T12:30:00"
.The
parse()
andformat()
methods are available for all date/time related objects (e.g.LocalDate
orZonedDateTime
)