Search code examples
javaandroiddatesimpledateformatdate-format

Android SimpleDateFormat problem


SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
Date date = (Date)formatter.parse("2011-09-13");
Log.e(MY_DEBUG_TAG, "Output is "+ date.getYear() + " /" + date.getMonth() + " / "+ (date.getDay()+1));

Is out putting

09-13 14:20:18.740: ERROR/GoldFishActivity(357): Output is 111 /8 / 3

What is the issue?


Solution

  • The methods you are using in the Date class are deprecated.

    • You get 111 for the year, because getYear() returns a value that is the result of subtracting 1900 from the year i.e. 2011 - 1900 = 111.
    • You get 3 for the day, because getDay() returns the day of the week and 3 = Wednesday. getDate() returns the day of the month, but this too is deprecated.

    You should use the Calendar class instead.

    SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
    Date date = (Date)formatter.parse("2011-09-13");        
    Calendar cal = Calendar.getInstance();  
    cal.setTime(date);
    Log.e(MY_DEBUG_TAG, "Output is "+ cal.get(Calendar.YEAR)+ " /" + (cal.get(Calendar.MONTH)+1) + " / "+ cal.get(Calendar.DAY_OF_MONTH));