Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android set DatePicker to a certain date

I have 3 strings containing day, month and year values. For example:

String mday = "02";
String mmonth="07";
String myear="2013";

I need to set the DatePicker in my activity to a month from the date above. I do not mean just add 1 to the mmonth value... in case of day 31 I would end up with an invalid date. So I need some way to increment the date (the valid way) and set the DatePicker with it's value. I am aware that setting the datePicker with Int values is done like this:

DatePicker datepicker = (DatePicker) findViewById(R.id.datePicker1); 
datepicker.init(iYear, iMonth, iDay, null); 
// where iYear,iMonth and iDay are integers

But how do I obtain the integer values of day,month and year of an incremented DATE by one month?

So between the first values (strings) and final values of incremented date(integers) what are the steps that I must make?

I assume I would have to use a Calendar. So my code should look like this:

Integer iYear, iMonth, iDay = 0;
String mday = "02";
String mmonth="07";
String myear="2013";

Calendar cal = Calendar.getInstance();
cal.set(Integer.parseInt(myear), Integer.parseInt(mmonth), Integer.parseInt(mday));
cal.add(Calendar.MONTH, 1);
// here I should get the values from cal inside the iYear, iMonth, iDay, but I do not seem to succeed.

DatePicker datepicker = (DatePicker) findViewById(R.id.datePicker1); 
datepicker.init(iYear, iMonth, iDay, null); 

if I do:

datepicker.init(cal.YEAR, cal.MONTH, cal.DATE, null);

then application crashes. What should I do? How to set this incremented by a month date into my DatePicker?

UPDATE I changed my test code to this:

    Calendar cal = Calendar.getInstance();
    cal.set(2013, 05, 23);
    cal.add(Calendar.MONTH, 1);

    int xxday = cal.get(Calendar.DATE);
    int xxmonth = cal.get(Calendar.MONTH);
    int xxyear = cal.get(Calendar.YEAR);

    datepicker.init(xxyear, xxmonth, xxday, null);

but Now the datePicker is set to one month from NOW instead of one month from the wanted date So instead of (2013-06-23) I have (2013-09-23). I assume it's because of

    int xxmonth = cal.get(Calendar.MONTH);

how can I get the real month from a Calendar cal; ?

like image 652
user1137313 Avatar asked Aug 03 '13 00:08

user1137313


2 Answers

DatePicker class has a method updateDate(year, month, dayOfMonth) which you can use to set a date in your DatePicker as shown below:

DatePicker datePicker = (DatePicker) findViewById(R.id.datePicker1);
datePicker.updateDate(2016, 5, 22);
like image 52
Hradesh Kumar Avatar answered Oct 09 '22 18:10

Hradesh Kumar


Calendar month is 0 based. So month 07 is August.

like image 34
Kenny C Avatar answered Oct 09 '22 16:10

Kenny C