Calendar.MONTH gives wrong value
Asked Answered
N

6

15

I'm trying to get the actual month from the Calendar using the following:

Calendar c = Calendar.getInstance();          
String time = String.valueOf(c.get(Calendar.MONTH));

According the system settings "Settings --> Date & Time" actual month is 10 while get(Calendar.MONTH) returns 09.

Nolte answered 13/10, 2013 at 17:24 Comment(1)
You need to subtract 1 from it since months go from 0..11Occupy
D
37

Keep in mind that months values start from 0, so October is actually month number 9.

http://docs.oracle.com/javase/1.4.2/docs/api/java/util/Calendar.html#MONTH

Durative answered 13/10, 2013 at 17:25 Comment(0)
S
9

Calendar.MONTH returns month which is zero based that is why it is giving 1 less than actual month Add 1 to get correct value

String time = String.valueOf(c.get(Calendar.MONTH)+1);
Standfast answered 13/10, 2013 at 17:26 Comment(0)
R
4

Calendar.MONTH

returns

0 for 1st month (jan)
1 for 2nd month (feb)
.
.
11 for 12th month (dec)

Docs

So change your code to

String time = String.valueOf(c.get(Calendar.MONTH)+1);// added 1 
Roche answered 13/10, 2013 at 17:26 Comment(0)
L
0

Calendar.MONTH value starts from 0 to 11 not 1 to 12.

You may check the value of Calendar.JANUARY is 0 not 1.

Refer: http://developer.android.com/reference/java/util/Calendar.html#JANUARY

Leucotomy answered 13/10, 2013 at 17:32 Comment(0)
B
0

I suggest trying

@Override
public void onSelectedDayChange(CalendarView view, int year, int month, int day) {
Toast.makeText(getApplicationContext(), month+1 + "/" + day  + "/" + year, Toast.LENGTH_SHORT).show();
calDate = month+1 + "/" + day + "/" + year; }
});
Bryantbryanty answered 6/6, 2016 at 17:19 Comment(1)
Concatenating strings to make dates is unsafe for internationalization and a terrible practice. Please use the system library date formatters.Dynel
G
0

use this

    public void DateDialog(){

    DatePickerDialog.OnDateSetListener listener=new DatePickerDialog.OnDateSetListener() {
        @Override
        public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth)
        {
            int Month;
            Month=monthOfYear+1;
            fromDate.setText(year + "-" + Month + "-" + dayOfMonth);
        }};
    DatePickerDialog dpDialog=new DatePickerDialog(getActivity(), listener, year, month, day);
    dpDialog.getDatePicker().setMinDate(mcalendar.getTimeInMillis());
    dpDialog.show();
}
Gonidium answered 22/6, 2018 at 11:18 Comment(1)
How does this differ from the existing answers? Some comments might be useful.Antispasmodic

© 2022 - 2024 — McMap. All rights reserved.