Converting a date string to a DateTime object using Joda Time library
I have a date as a string in the following format "04/02/2011 20:27:05"
. I am using Joda-Time library and would like to convert it to DateTime
object. I did:
DateTime dt = new DateTime("04/02/2011 20:27:05")
But I'm getting the following error :
Invalid format: "04/02/2011 14:42:17" is malformed at "/02/2011 14:42:17"
How to convert the above date to a DateTime
object?
Use DateTimeFormat
:
DateTimeFormatter formatter = DateTimeFormat.forPattern("dd/MM/yyyy HH:mm:ss");
DateTime dt = formatter.parseDateTime(string);
I know this is an old question, but I wanted to add that, as of JodaTime 2.0, you can do this with a one-liner:
DateTime date = DateTime.parse("04/02/2011 20:27:05",
DateTimeFormat.forPattern("dd/MM/yyyy HH:mm:ss"));
DateTimeFormat.forPattern("dd/MM/yyyy HH:mm:ss").parseDateTime("04/02/2011 20:27:05");
From comments I picked an answer like and also adding TimeZone:
String dateTime = "2015-07-18T13:32:56.971-0400";
DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss.SSSZZ")
.withLocale(Locale.ROOT)
.withChronology(ISOChronology.getInstanceUTC());
DateTime dt = formatter.parseDateTime(dateTime);