Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Convert String to LocalDateTime in Java [2 ways]

In this post, I will be sharing how to convert String to Localdatetime in Java. LocalDateTime provides date-time without time-zone information. This class is thread-safe and immutable. It is represented in the ISO-8601 calendar system. LocalDateTime class was introduced in Java8. Let's dive deep into the topic:

Read Also: [Solved] Unable to obtain LocalDateTime from TemporalAccessor

Convert String to LocalDateTime in Java

1. Using parse() method


We can easily convert String to LocalDateTime in Java using LocalDateTime's static parse() method as shown below in the example.

 import java.time.LocalDateTime;

public class ConvertStringToLocalDateTime {
public static void main(String args[]) {
// Given String
String dateString = "2018-07-18T08:20:25";

// Convert String to LocalDateTime Object using parse() method
LocalDateTime localdatetime = LocalDateTime.parse(dateString);

// Display LocalDateTime object
System.out.println("Converted String to LocalDateTime: " + localdatetime);
}
}


Output:
Converted String to LocalDateTime: 2018-07-18T08:20:25


Note: The string passed in the parse() method must represent a valid date-time otherwise DateTimeParseException will be thrown.


2. Convert String to LocalDateTime with custom format


We can easily convert String to LocalDateTime with a custom format using the overloaded static parse() method. The overloaded static parse() method takes a String and a DateTimeFormatter as a parameter shown below in the example.

 import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

public class ConvertStringToLocalDateTime2 {
public static void main(String args[]) {
// Given String
String dateString = "2016/09/18 18:11:25";

// Specify date format using DateTimeFormatter
DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss");

// Convert String to LocalDateTime Object using overloaded static parse() method
LocalDateTime localdatetime = LocalDateTime.parse(dateString, dateTimeFormatter);

// Printing LocalDateTime object
System.out.println("Converted String to LocalDateTime: " + localdatetime);
}
}


Output:
Converted String to LocalDateTime: 2016-09-18T18:11:25


That's all for today. Please mention in the comments if you have any questions related to how to convert String to LocalDateTime in Java with examples.


This post first appeared on Java Hungry, please read the originial post: here

Share the post

Convert String to LocalDateTime in Java [2 ways]

×

Subscribe to Java Hungry

Get updates delivered right to your inbox!

Thank you for your subscription

×