0

trying to parse the String "2019-08-21 9:04:08" into a Calender object.

I am getting the result Mon Dec 31 09:04:08 GMT 2018 from calender.getTime()

Here is how I parse it

Calendar cal = Calendar.getInstance();
    SimpleDateFormat sdf = new SimpleDateFormat("YYYY-MM-DD hh:mm:ss");
    try {
        cal.setTime(sdf.parse("2019-08-21 9:04:08"));
    } catch (ParseException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }// all done
    return cal;
}
Daniel Haughton
  • 1,085
  • 5
  • 20
  • 45
  • A Calendar just keeps a Date which just keep a long ms. It has no inherent format, and delivers your local time to Greenwich Mean Time. So you evidently live on the 0 meridian, in England. Parsing from a format assumes a locale/clock. Also you need **HH** for 24 hours time. – Joop Eggen Dec 19 '19 at 12:37
  • Please see the docs at https://docs.oracle.com/javase/8/docs/api/java/text/SimpleDateFormat.html . – rajah9 Dec 19 '19 at 12:41
  • By the way, the newer time classes are a bit overwhelming but much better. – Joop Eggen Dec 19 '19 at 12:42
  • Does this answer your question? [Java string to date conversion](https://stackoverflow.com/questions/4216745/java-string-to-date-conversion) – rajah9 Dec 19 '19 at 12:47

1 Answers1

3

You are not using the right parser format. The one you need is "yyyy-MM-dd hh:mm:ss". The format "YYYY" is week-based calendar year, which is not what you want. As @rajah9 points out, the documentation can guide further regarding the use of SimpleDateFormat.

Alain Cruz
  • 4,757
  • 3
  • 25
  • 43