简体   繁体   中英

how to set start date and end date in android

How to set Start Date and End Date in TextView and also how to set date listener on both TextView ?

tv_fromDate.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                tv_fromDate.setText(getCurrentDate());
            }
        });
        tv_toDate.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                tv_toDate.setText(getCurrentDate());
            }
        });

Use SimpleDateFormat for formatting, use Calendar class for date related operation and DatePickerDialog for selecting date on TextView click.

UPDATED: There are some changes you will need in current code:

tv_fromDate.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            getCurrentDate(tv_fromDate);
        }
 });
 tv_toDate.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            getCurrentDate(tv_toDate);
        }
 });

and this is the code you will need in the method:

public void getCurrentDate(TextView tvDate) {

    DatePickerDialog datePickerDialog = new DatePickerDialog(getContext(), new DatePickerDialog.OnDateSetListener() {
        @Override
        public void onDateSet(datePicker, year, monthOfYear, dayOfMonth) {
            Calendar calendar = Calendar.getInstance();
            calendar.set(Calendar.YEAR, year);
            calendar.set(Calendar.MONTH, monthOfYear);
            calendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd-MM-yyyy");
            tvDate.setText(simpleDateFormat.format(calendar.getTime()));
        }
    }, Calendar.getInstance().get(Calendar.YEAR), Calendar.getInstance().get(Calendar.MONTH), Calendar.getInstance().get(Calendar.DAY_OF_MONTH));
        datePickerDialog.show();
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM