开发者

Android SimpleDateFormat problem

SimpleDate开发者_运维问答Format 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?


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));


Read the javadoc of java.util.Date carefully.

getYear returns the number of years since 1900.

getMonth returns the month, starting from 0 (0 = January, 1 = February, etc.).

getDay returns the day of week (0 = Sunday, 1 = Monday, etc.), not the day of month.

And all these methods are deprecated. You shouldn't use them anymore.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜