Search code examples
androidandroid-datepicker

datePicker.getMonth() +1 doesn't give expected result


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

BY adding 1 to the datePicker.getMonth(),i am getting month number

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

But when i removing the "1" i am getting month number output like

            jan-0,feb-01,mar-02

Solution

  • You want parentheses.

    (datePicker.getMonth()+1)
    

    Otherwise you are doing string concatenation.

    For example

    If getMonth() returns 0 (for January), then

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

    is

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

    But with parens

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