javaoracle-databasedatetimeformattingjodatime

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"


Solution

  • 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");
    }