datePicker.getMonth()+1不会给出预期的结果

时间:2011-08-07 07:46:05

标签: android android-datepicker

             Toast.makeText(getBaseContext(),
            "Date selected:" + datePicker.getMonth()+1+
            "/"+ datePicker.getDayOfMonth() +
            "/"+ datePicker.getYear() +"\n" +
            "Time Slected:" + timePicker.getCurrentHour() + 
            ":"+ timePicker.getCurrentMinute(),
            Toast.LENGTH_SHORT).show();

通过向datePicker.getMonth()添加1,我得到月份数

            output like->
            jan-01,feb-11,mar-21

但是当我删除“1”时,我会得到月份数输出

            jan-0,feb-01,mar-02

2 个答案:

答案 0 :(得分:7)

你想要括号。

(datePicker.getMonth()+1)

否则你正在进行字符串连接。

例如

如果getMonth()返回0(1月份),那么

"Date selected: " + datePicker.getMonth()+1

("Date selected: " + 0) + 1
= "Date selected: 0" + 1
= "Date selected: 01"

但是有了parens

"Date selected: " + (datePicker.getMonth()+1)
= "Date selected: " + (0+1)
= "Date selected: " + 1
= "Date selected: 1"

答案 1 :(得分:2)

从0开始索引月份。因此第一个月得到数字0,第二个得到1。