0

I want to parse the following date:

24 07 2017 3:47:57 AM

with the following format:

SimpleDateFormat df2 = new SimpleDateFormat("dd MM yyyy hh:mm:ss a");
df2.setTimeZone(TimeZone.getTimeZone("UTC"));
try {
    df2.parse(dateStr + " "+ sunrise);
}catch(ParseException e){
    e.printStackTrace();
}

But I get the following error:

java.text.ParseException: Unparseable date: "24 07 2017 3:47:57 AM"
Chandan Rai
  • 9,879
  • 2
  • 20
  • 28
farahm
  • 1,326
  • 6
  • 32
  • 70
  • 1
    I can't reproduce that error. – David Pérez Cabrera Jul 24 '17 at 10:45
  • This code works. It is possible that you changed something? – Davide Lorenzo MARINO Jul 24 '17 at 10:47
  • Possible duplicate of [java.text.ParseException: Unparseable date: "01:19 PM"](https://stackoverflow.com/questions/25524284/java-text-parseexception-unparseable-date-0119-pm) – Ole V.V. Jul 24 '17 at 18:13
  • Possible duplicate of [Unable to parse DateTime-string with AM/PM marker](https://stackoverflow.com/questions/3618676/unable-to-parse-datetime-string-with-am-pm-marker) – Ole V.V. Jul 24 '17 at 18:15
  • 1
    As an aside, I recommend you drop the outdated classes `Date` and `SimpleDateFormat`. The modern Java date and time API, known as `java.time` or JSR-310, is much more programmer friendly, generally much nicer to work with. – Ole V.V. Jul 24 '17 at 18:53

1 Answers1

3

One possibility is that your default Locale has different symbols for AM/PM. When constructing a date format you should always supply a Locale unless you really want to use the system's default Locale, for example:

SimpleDateFormat df2 = new SimpleDateFormat("dd MM yyyy hh:mm:ss a", Locale.US)
Vadim Beskrovnov
  • 941
  • 6
  • 18
  • Tested with Locale.TRADITIONAL_CHINESE, it actually throws a ParseException. With my default Locale it works well. – Massimo Jul 24 '17 at 10:51
  • Yap, that's the issue. Thanks a lot! :) – farahm Jul 24 '17 at 10:54
  • Even if you want the JVM’s default locale, I will prefer you explicitly give `Locale.getDefault()` so the reader too knows you’ve made a conscious choice and you didn’t just forget to choose. – Ole V.V. Jul 24 '17 at 18:56