How can I parse/format dates with LocalDateTime? (Java 8)
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
)
Convert String to LocalDateTime Java 8
You don't need to specify a DateTimeFormatter
in this case because the default one will be used if you don't pass one at all:
public static void main(String[] args) {
String dateStr = "2020-08-17T10:11:16.908732";
// the following uses the DateTimeFormatter.ISO_LOCAL_DATE_TIME implicitly
LocalDateTime dateTime = LocalDateTime.parse(dateStr);
System.out.println(dateTime);
}
That code will output 2020-08-17T10:11:16.908732
.
If you are insisting on using a custom DateTimeFormatter
, consider the T
by single-quoting it in the pattern and don't use nanosecond parsing (n
) for parsing fractions of second (S
), the result might be wrong otherwise.
Do it like this:
public static void main(String[] args) {
String dateStr = "2020-08-17T10:11:16.908732";
DateTimeFormatter format = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSSSS");
LocalDateTime dateTime = LocalDateTime.parse(dateStr, format);
System.out.println(dateTime);
}
with the same output as above.
Note:
The result of using the pattern "yyyy-MM-dd'T'HH:mm:ss.nnnnnn"
would not be equal to the parsed String
, instead, it would be
2020-08-17T10:11:16.000908732
Convert String to LocalDateTime in Java
I'd say use Locale.ROOT and don't forget the Z in the DateTimeFormatter class
String dateString = "Fri, 07 Aug 2020 18:00:00 +0000";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("E, dd MMM yyyy HH:mm:ss Z", Locale.ROOT);
LocalDateTime parsedDate = LocalDateTime.parse(dateString, formatter);
Problem with convert String to LocalDateTime
Your DateTime pattern in your DateTimeFormatter causes the problem you see here. You need to use HH
instead of hh
hh
: This is an hour-of-day pattern that uses a 12 hour clock, with AM/PM indications.HH
: This is an hour-of-day pattern that uses a 24 hour clock. Takes input between 0-23
Sidenote, the zones you use seem to be invalid.
The corresponding zones would be
Europe/London
America/Los_Angeles
Australia/Sydney
String to LocalDate
As you use Joda Time, you should use DateTimeFormatter
:
final DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MMM-dd");
final LocalDate dt = dtf.parseLocalDate(yourinput);
If using Java 8 or later, then refer to hertzi's answer
Convert string into LocalDateTime
I think this will answer your question:
val stringDate = expiration_button.text.toString()
val formatter = DateTimeFormatter.ofPattern("dd/MM/yyyy hh:mm");
val dt = LocalDate.parse(stringDate, formatter);
Edit 1:
It's probably crashing because you are using a 12hr Hour, instead of a 24hr pattern.
Changing the hour to 24hr pattern by using a capital H should fix it:
val dateTime = LocalDateTime.parse(stringDate, DateTimeFormatter.ofPattern("dd/MM/yyyy HH:mm"));
Convert string to LocalDateTime or OffsetDateTime
Case-sensitive
You are using uppercase 'YYYY' which is the week year
. Try with lowercase 'yyyy':
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MMM-yyyy HH:mm");
Locale
And specify a Locale
for the human language and cultural norms used in translating the name of month.
DateTimeFormatter formatter =
DateTimeFormatter
.ofPattern("dd-MMM-yyyy HH:mm")
.withLocale( Locale.US );
See this code run live at IdeOne.com.
2020-07-17T12:12
Convert String to LocalDateTime with zoned time
The LocalDateTime
class is a date-time representation which is unaware of time zones and it's only logical that the LocalDateTimeDeserializer
ignores any time zone information in the source data.
To account for the time zone you could use the InstantDeserializer.OFFSET_DATE_TIME
deserializer (DateTimeFormatter.ISO_OFFSET_DATE_TIME
is actually the format of the source date time you have) and have its result converted to LocalDateTime
within a desired zone. This can be wrapped in a custom deserializer for ease of use, e.g.
class SmartLocalDateTimeDeserializer extends StdDeserializer<LocalDateTime> {
private final InstantDeserializer<OffsetDateTime> delegate = InstantDeserializer.OFFSET_DATE_TIME;
public SmartLocalDateTimeDeserializer() {
super(LocalDateTime.class);
}
@Override
public LocalDateTime deserialize(JsonParser p,
DeserializationContext ctxt) throws IOException, JsonProcessingException {
final OffsetDateTime result = delegate.deserialize(p, ctxt);
return result.atZoneSameInstant(ZoneId.systemDefault()).toLocalDateTime();
}
}
...
javaTimeModule.addDeserializer(LocalDateTime.class, new SmartLocalDateTimeDeserializer());
Related Topics
How to Do Page Flip/Turn/Curl Effect in Android
Load Large Images with Picasso and Custom Transform Object
Difference Between Content_Main.Xml and Activity_Main.Xml
Android Listview Setselection() Does Not Seem to Work
Android Studio: Unable to Start the Daemon Process
How to Tell Which App Was Selected by Intent.Createchooser
Start a Fragment via Intent Within a Fragment
Uncaught Exception in Firebase Runloop (3.0.0)
How to Create Always-Top Fullscreen Overlay Activity in Android
How to Run Opencv Code Without Opencv Manager
How to Set Spinner Default Value to Null
Find Out the Running Process Id by Package Name
How to Retrieve the Data from Asynctasks Doinbackground()
Error Type 3: Activity Class {...} Does Not Exist
How to Change the Color of the Tabs Indicator Text in Android