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?
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
)Both answers above explain very well the question regarding string patterns. However, just in case you are working with ISO 8601 there is no need to apply
DateTimeFormatter
since LocalDateTime is already prepared for it:Convert LocalDateTime to Time Zone ISO8601 String
Convert from ISO8601 String back to a LocalDateTime
You can also use
LocalDate.parse()
orLocalDateTime.parse()
on aString
without providing it with a pattern, if theString
is in ISO-8601 format.for example,
Output,
and use
DateTimeFormatter
only if you have to deal with other date patterns, For example, dd MMM uuuu represents the day of the month (two digits), three letters of the name of the month (Jan, Feb, Mar,...), and a four-digit year:Output
also remember that the
DateTimeFormatter
object is bidirectional; it can both parse input and format output.Output
(see complete list of Patterns for Formatting and Parsing DateFormatter)