如何在android中比较当前时间和所选时间

时间:2017-07-06 10:09:18

标签: android validation time android-timepicker

我有时间选择器,我不想从中选择以前的时间。

这意味着如果我在当前时间之前选择时间则无法显示。我不想在当前时间之前显示时间。

public class ProfileDetail extends AppCompatActivity {
    Toolbar toolbar;
    String description, str_requirement, str_date, str_time, str_noofperson, str_address;
    TextView txt_description;
    EditText et_requirment, date_pick, time_set, et_no_of_person, et_address_service;
    Button btn_submit;
    int mYear, mMonth, mDay, mHour, mMinute;
    private Calendar cal;
    DateFormat fmtDateAndTime = DateFormat.getTimeInstance();

    @RequiresApi(api = Build.VERSION_CODES.N)
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.profile_details);
        Bundle extras = getIntent().getExtras();
        description = extras.getString("description");
        txt_description = (TextView) findViewById(R.id.txtservicedetails);
        toolbar = (Toolbar) findViewById(R.id.toolbarforprofile);
        setSupportActionBar(toolbar);
        cal = Calendar.getInstance();
        mDay = cal.get(Calendar.DAY_OF_MONTH);
        mMonth = cal.get(Calendar.MONTH);
        mYear = cal.get(Calendar.YEAR);
        mHour = cal.get(Calendar.HOUR_OF_DAY);
        mMinute = cal.get(Calendar.MINUTE);
        et_requirment = (EditText) findViewById(R.id.editText_requirement);
        et_no_of_person = (EditText) findViewById(R.id.et_noofperson);
        et_address_service = (EditText) findViewById(R.id.et_serviceaddress);
        time_set = (EditText) findViewById(R.id.et_time);
        date_pick = (EditText) findViewById(R.id.et_dateof_visit);
        btn_submit = (Button) findViewById(R.id.btn_submit);


        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setDisplayShowHomeEnabled(true);
        toolbar.setTitle("Need-Hlp");
        toolbar.setTitleTextColor(Color.WHITE);
        txt_description.setText(description);
        //date_pick.setInputType(InputType.TYPE_NULL);
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intentfromprevious = new Intent(ProfileDetail.this, NavigationDrawer.class);
                intentfromprevious.putExtra("description", description);
                intentfromprevious.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                intentfromprevious.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
                intentfromprevious.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
                startActivity(intentfromprevious);

            }
        });

        date_pick.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showDialog(0);
            }
        });

        final TimePickerDialog.OnTimeSetListener t = new TimePickerDialog.OnTimeSetListener() {
            public void onTimeSet(TimePicker view, int hourOfDay, int minute) {

                cal.set(Calendar.HOUR_OF_DAY, hourOfDay);
                cal.set(Calendar.MINUTE, minute);


                updateLabel();
            }
        };

        time_set.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // Get Current Time


                new TimePickerDialog(ProfileDetail.this, t, cal
                        .get(Calendar.HOUR_OF_DAY), cal
                        .get(Calendar.MINUTE), true).show();
            }
        });
        //final TextView textView = (TextView)findViewById(R.id.textview23);


        //////Submit button onclicklistener
        btn_submit.setOnClickListener(new View.OnClickListener()

        {
            @Override
            public void onClick(View v) {

                str_date = date_pick.getText().toString();
                if (et_requirment.getText().toString().equals("")) {
                    et_requirment.setError("Requirement cannot be blank");
                    et_requirment.requestFocus();
                    return;
                }
                if (str_date.isEmpty() || str_date.length() == 0 || str_date.equals("") || str_date == null) {
                    Toast.makeText(ProfileDetail.this, "Date cannot be blank", Toast.LENGTH_SHORT).show();
                    //date_pick.setError("Date cannot be blank");
                    return;

                }

                if (time_set.getText().toString().equals("")) {
                    Toast.makeText(ProfileDetail.this, "Time cannot be blank", Toast.LENGTH_SHORT).show();
                    //time_set.setError("Time cannot be blank");
                    //edittext_phone.requestFocus();
                    return;
                }

                if (et_no_of_person.getText().toString().toString().equals("")) {
                    et_no_of_person.setError("No of person cannot be blank");
                    //edittext_phone.requestFocus();
                    return;
                }
                if (et_address_service.getText().toString().equals("")) {
                    et_address_service.setError("Address cannot be blank");
                    //edittext_Password.requestFocus();
                    return;
                }


                if (!et_requirment.getText().toString().trim().equals("") && !et_no_of_person.getText().toString().trim().equals("") && !et_address_service.getText().toString().equals("")) {


                    Toast.makeText(ProfileDetail.this, "You Request Submitted", Toast.LENGTH_SHORT).show();
                    Intent intentforlist = new Intent(ProfileDetail.this, NavigationDrawer.class);
                    intentforlist.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    intentforlist.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
                    intentforlist.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
                    startActivity(intentforlist);
                }

            }

        });

    }

    private void updateLabel() {
        Calendar c = Calendar.getInstance();

        String time = "23:00";
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date timeCompare = null;
        Date currentTimes = new Date();
        int comareResult = timeCompare.compareTo(currentTimes);
        try {

            if (comareResult == 0) {
                timeCompare = sdf.parse(time);
                time_set.setText(time);
            }

        } catch (ParseException e) {
            e.printStackTrace();
        }


    }

    @Override
    @Deprecated
    protected Dialog onCreateDialog(int id) {
        //return new DatePickerDialog(this, datePickerListener, mYear, mMonth, mDay);


        DatePickerDialog _date = new DatePickerDialog(this, datePickerListener, mYear, mMonth, mDay) {
            @Override
            public void onDateChanged(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
                if (year < mYear)
                    view.updateDate(mYear, mMonth, mDay);

                if (monthOfYear < mMonth && year == mYear)
                    view.updateDate(mYear, mMonth, mDay);

                if (dayOfMonth < mDay && year == mYear && monthOfYear == mMonth)
                    view.updateDate(mYear, mMonth, mDay);


            }
        };
        return _date;

    }


    private DatePickerDialog.OnDateSetListener datePickerListener = new DatePickerDialog.OnDateSetListener() {
        public void onDateSet(DatePicker view, int selectedYear,
                              int selectedMonth, int selectedDay) {


            date_pick.setText(+selectedDay + " / " + (selectedMonth + 1) + " / "
                    + selectedYear);
        }
    };


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main, menu);

        MenuItem item1 = menu.findItem(R.id.action_cart);
        MenuItemCompat.setActionView(item1, R.layout.count);
        // notificationCount1 = (RelativeLayout) MenuItemCompat.getActionView(item1);
        return super.onCreateOptionsMenu(menu);
    }
}

2 个答案:

答案 0 :(得分:1)

要阻止用户过去选择一个时间(我认为这就是你要求的!)就这样做:

myDatePicker.setMinDate(System.currentTimeMillis(););

答案 1 :(得分:0)

我从您的问题中了解到,您不希望从当前的日历时间中选择上一个时间。为了解决您的问题,您可以使用以下代码

datePicker.setMinDate(System.currentTimeMillis() - 1000);

记住:

从源代码开始,最小日期必须在当前日期之前,而不是等于当前日期。所以你只需要从现在开始减去足够的时间