1

I have a date which is stored in string format, under the following convention yyyy-mm-dd, and I want to get the month, so this is what I'm doing

    String dateS = j.getString(key);
    Calendar cal = Calendar.getInstance();
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-mm-dd");

    if ("null".equals(dateS))
        dateS = j.getString("created");

    try {
        cal.setTime(sdf.parse(dateS));
        System.out.println("parsed: " + sdf.parse(dateS));
        System.out.println("original: " + dateS);
        System.out.println("Month: " + cal.get(Calendar.MONTH));
    } catch (ParseException e) {
        // null, for now don't do anything, but this should never happen
    }

And this is the output:

parsed: Sun Jan 19 00:02:00 EST 2014
original: 2014-02-19
Month: 0

As you can see, it's not parsing it into the right format, what am I doing wrong? is new SimpleDateFormat("yyyy-mm-dd"); not the right way to do it?

Stupid.Fat.Cat
  • 10,755
  • 23
  • 83
  • 144
  • 3
    Use "yyyy-MM-dd" format. – RaviH Feb 19 '14 at 17:10
  • This seems odd: `"null".equals(dateS)`. Does j.getString(key) return a string "null" or does it return a `null` value. If a `null` value then the if statement should be `if (dateS == null)` – DwB Feb 19 '14 at 17:13
  • @DwB normally that would be the case, but this is a string value that I get from a JSONObject, so it's actually not a null object but a string, I know, it's silly, but that's the way they had it set up – Stupid.Fat.Cat Feb 19 '14 at 17:14
  • in date format "mm" implies minute. For month you should use yyyy-MM-dd. For details refer the java docs, even though https://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html. – akshaya pandey Nov 07 '17 at 08:14

1 Answers1

3

Remember that 'm' means minutes and 'M' means months

http://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html

Jorge_B
  • 9,712
  • 2
  • 17
  • 22