Convert a Date String to a DateTime (from Joda Time) in Java
This post will discuss how to convert a date string to a Joda Time DateTime object in Java.
Before the introduction of to java.time package with Java 8, the standard date and time classes are very poor. The Joda-Time library provides a quality replacement for the date and time classes for Java.
To parse a date-time from the given text into a new DateTime object, you can simply use the DateTimeFormatter.parseDateTime() method. To create a formatter from a pattern string, you can call the static factory method DateTimeFormat.forPattern().
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
import org.joda.time.DateTime; import org.joda.time.format.DateTimeFormat; public class Main { public static void main(String[] args) { String s = "2017-12-24 14:17:21"; DateTime datetime = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss") .parseDateTime(s); System.out.println(datetime); } } |
Output (will vary):
2017-12-24T14:17:21.000-10:30
To use a specified time zone for parsing, use the withZone(DateTimeZone) method.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
import org.joda.time.DateTime; import org.joda.time.DateTimeZone; import org.joda.time.format.DateTimeFormat; import org.joda.time.format.DateTimeFormatter; public class Main { public static void main(String[] args) { String date = "2017-12-22 14:17:21"; DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss") .withZone(DateTimeZone.UTC); DateTime datetime = formatter.parseDateTime(date); System.out.println(datetime); } } |
Output (will vary):
2017-12-22T14:17:21.000Z
That’s all about converting a date string to a Joda Time DateTime object in Java.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)