Android SimpleDateFormat问题

Mit*_*ran 2 java android date-format simpledateformat

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));
Run Code Online (Sandbox Code Playgroud)

出去了

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

有什么问题?

dog*_*ane 6

您在Date该类中使用的方法已弃用.

  • 你今年得到111,因为getYear()返回的值是从年份减去1900的结果,即2011 - 1900 = 111.
  • 你每天得3,因为getDay()返回星期几和3 = Wednesday.getDate()返回该月的某一天,但这也是不推荐使用的.

您应该使用Calendar该类.

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));
Run Code Online (Sandbox Code Playgroud)