2

I'm trying to parse date "10/13/2014 08:06 AM" Here is my code:

public static LocalDateTime parseDateTime(String dateAndTime) {
    try {
        if (dateAndTime.contains("-")) {
            return LocalDateTime.parse(dateAndTime.toUpperCase(), DateTimeFormat.forPattern("yyyy-MM-dd hh:mm aa"));
            //return DateTimeFormat.forPattern("yyyy-MM-dd hh:mm aa").parseDateTime(dateAndTime.toUpperCase());
        } else {
            return LocalDateTime.parse(dateAndTime.toUpperCase(), DateTimeFormat.forPattern("MM/dd/yyyy hh:mm aa"));
            //return DateTimeFormat.forPattern("MM/dd/yyyy hh:mm aa").parseDateTime(dateAndTime.toUpperCase());
        }
    } catch (IllegalArgumentException e) {
        e.printStackTrace();
        return null;
    }
}

My parser fail:

java.lang.IllegalArgumentException: Invalid format: "10/13/2014 08:06 AM" is malformed at "AM"

Please help to investigate.

I'm using Android 4.4.4 and JodaTime 2.3

4
  • Sidenote: I'd probably use SimpleDateFormat instead. No need to add JodaTime. docs.oracle.com/javase/7/docs/api/java/text/… Commented Oct 13, 2014 at 20:51
  • I'am using it everywhere in my project. Especially for calculations such as plusHours Commented Oct 13, 2014 at 21:01
  • There's Calendar & DateUtils for that: developer.android.com/reference/android/text/format/…. Commented Oct 13, 2014 at 21:03
  • Guys, questions is about JodaTime. I know that Android has it's own utils... Commented Oct 13, 2014 at 21:19

1 Answer 1

3

I don't know what your locale is, but I can reproduce your problem with a locale like new Locale("hi", "IN") (my own system locale is different). So the solution for your problem is to specifiy the locale to English because text like "AM" is locale-specific and mainly used in English.

LocalDateTime ldt =
  LocalDateTime.parse(
    dateAndTime.toUpperCase(), 
    DateTimeFormat.forPattern("MM/dd/yyyy hh:mm aa").withLocale(Locale.ENGLISH));
Sign up to request clarification or add additional context in comments.

1 Comment

That was a solution! Thanks Meno!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.