Search code examples
androidandroid-calendarandroid-datepicker

Calendar giving wrong date and time


This is a very annoying issue I've been facing for a few days now. I'm using the Genymotion emulator. The code is as follows:

        DatePicker dp = (DatePicker) d.findViewById(R.id.datePicker1);
        TimePicker tp = (TimePicker) d.findViewById(R.id.timePicker1);

        Calendar.getInstance();

        selectedDate = Calendar.YEAR + "/" + Calendar.MONTH + "/" + Calendar.DAY_OF_MONTH;
        selectedTime = Calendar.HOUR_OF_DAY + ":" + Calendar.MINUTE;

        dp.init(Calendar.YEAR, Calendar.MONTH, Calendar.DAY_OF_MONTH, new OnDateChangedListener()
        {
            @Override public void onDateChanged(DatePicker view, int year, int monthOfYear, int dayOfMonth)
            {
                selectedDate = dayOfMonth + "/" + monthOfYear + 1 + "/" + year;
            }
        });

When I debug the above code and watch the values of Calendar.MONTH and Calendar.DAY_OF_MONTH, they're wrong. Same goes for hour and minute values (current time is 17:25 but the Calendar gives 11:12).

What am I doing wrong? TimerPicker is initialized to the correct time on the same device, automatically.


Solution

  • Calendar.HOUR_OF_DAY is a constant assigned by Android.

    When you use Calendar.HOUR_OF_DAY it doesn't give you the current hour it gives you the value that Android assigned to constant Calendar.HOUR_OF_DAY

    If you want to get the current time you need to do

    Calendar cal = Calendar.getInstance();
    

    and then if you want to retrieve the current hour retrieve it like

    cal.get(Calendar.HOUR_OF_DAY);
    

    This will give you the current hour same goes for any other value.

    Note: When you retrieve MONTH it will give you 1 less value For eg. for May it will return 4 because it is based on 0 index value.

    So in order to get today's date and time you have to do

    selectedDate = cal.get(Calendar.YEAR) + "/" + (cal.get(Calendar.MONTH)+1) + "/" + cal.get(Calendar.DAY_OF_MONTH);
    selectedTime = cal.get(Calendar.HOUR_OF_DAY) + ":" + cal.get(Calendar.MINUTE);