Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understanding JodaTime DateTime.parse(string, formatter)

Does the style of the formatter in the parse method of the DateTime class have to match the exact style of the string? For instance, I'm getting a TimeStamp object from the database (Oracle) and converting it to a string. In the database the TimeStamp is stored like this

08-AUG-12 12.00.00.000000000 AM

I set my formatter to this style

String pattern = "dd-MMM-yy";

I get this exception

java.lang.IllegalArgumentException: Invalid format: "08-AUG-12 12.00.00 AM" is malformed at " 12.00.00 AM"

org.joda.time.format.DateTimeFormatter.parseDateTime(DateTimeFormatter.java:866)

org.joda.time.DateTime.parse(DateTime.java:144)

What exactly does this mean and how would I go about fixing it? When I set my formatter to "yy-MMM-dd hh.mm.ss aa" I don't get an exception but it prints in the browser like this: 2008-08-12T00:00:00.000-04:00, but I need for it to print out as "dd-MMM-yy hh:mm:ss aa"

like image 754
Robert Avatar asked Aug 28 '12 20:08

Robert


People also ask

What is JodaTime?

Joda-Time is an API created by joda.org which offers better classes and having efficient methods to handle date and time than classes from java. util package like Calendar, Gregorian Calendar, Date, etc. This API is included in Java 8.0 with the java.

Is Joda DateTime thread safe?

DateTime is thread-safe and immutable, provided that the Chronology is as well. All standard Chronology classes supplied are thread-safe and immutable.

How do I change the date format in Joda-Time?

I think this will work, if you are using JodaTime: String strDateTime = "11/15/2013 08:00:00"; DateTime dateTime = DateTime. parse(strDateTime); DateTimeFormatter fmt = DateTimeFormat. forPattern("MM/dd/YYYY"); String strDateOnly = fmt.


2 Answers

Use LocalDateTime instead:

String input = "08-AUG-12 12.00.00 AM";
String pattern = "dd-MMM-yy hh.mm.ss aa";

LocalDateTime localDateTime = LocalDateTime.parse(input, DateTimeFormat.forPattern(pattern));

EDIT

As a matter of fact you can do it with DateTime also:

private static String parseDateTime(String input){
     String pattern = "dd-MMM-yy hh.mm.ss aa";
     DateTime dateTime  = DateTime.parse(input, DateTimeFormat.forPattern(pattern));
     return dateTime.toString("dd-MMM-yy hh:mm:ss aa");
}
like image 169
Eugene Avatar answered Sep 21 '22 18:09

Eugene


Figured it out. To get the correct format, you have to call formatter.print(localDateTime object) and it worked.

like image 30
Robert Avatar answered Sep 21 '22 18:09

Robert