Karan Saxena Karan Saxena - 6 months ago 17
Android Question

how to extract date from calendar in Android?

I am trying to make an event planner application in Android. I have added the a calendar widget now what i want is that whenever a user clicks the add event button. It will go to a new activity screen and the date selected by the user in the calendar in the previous activity gets copied exactly to a text field. Can anyone help mein with this code?

P.S.- I have added two fragments on the main screen one for the calendar and one for the buttons. Thanx in advance.

Answer

If you mean DatePicker then this is how you get selected date, by registering a date selection listener

datePicker.init(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH), new DatePicker.OnDateChangedListener() {

    @Override
    public void onDateChanged(DatePicker datePicker, int year, int month, int dayOfMonth) {
                    Log.d("Date", "Year=" + year + " Month=" + (month + 1) + " day=" + dayOfMonth);

                }
            });

or you get the selected date anytime by :

 DatePicker datePicker = (DatePicker) findViewById(R.id.datePicker1);
 int day = datePicker.getDayOfMonth();
 int month = datePicker.getMonth() + 1;
 int year = datePicker.getYear();

or if you are using CalendarView then a simple getDate() call would do the trick. Now extract the day, month, year from that and pass it to the next activity via Intent

If you are using something else let us know.