How to set custom time in TimePicker

The TimePicker shows the current default time in the TimePicker, but what if I want to set the default time at select time as per my requirement.

Like its 11:10 as I write this, but in the TimePicker I like to show 01:00 by default (my average difference of 2 hours and minutes should only be 00)

static final int TIME_DIALOG_ID = 1;

    public  int year,month,day,hour,minute;  
    private int mYear, mMonth, mDay,mHour,mMinute; 

    public TimePickerActivity() {

            // Assign current Date and Time Values to Variables
            final Calendar c = Calendar.getInstance();
            mYear = c.get(Calendar.YEAR);
            mMonth = c.get(Calendar.MONTH);
            mDay = c.get(Calendar.DAY_OF_MONTH);
            mHour = c.get(Calendar.HOUR_OF_DAY);
            mMinute = c.get(Calendar.MINUTE);
    }

    private TimePickerDialog.OnTimeSetListener mTimeSetListener =
        new TimePickerDialog.OnTimeSetListener() {

        public void onTimeSet(TimePicker view, int hourOfDay, int min) {
            hour = hourOfDay;
            minute = min;

            String formattedMinutes = "" + min;
            String formattedHour = "" + hourOfDay;

            if (hourOfDay < 10) {
                formattedHour = "0" + hourOfDay;
            }

            if (min < 10) {
                formattedMinutes = "0" + min;
            }

            textTime.setText(formattedHour + ":" + formattedMinutes);
        }
    };

  @Override
  protected Dialog onCreateDialog(int id) {
    switch (id) {

    case TIME_DIALOG_ID:
        TimePickerDialog timePickerDialog = new TimePickerDialog(this, mTimeSetListener, mHour, mMinute, false);
        return timePickerDialog;
    }

    return null;
}

      

+3


source to share


2 answers


You can do it with the following code:



private TimePicker timePicker;

    timePicker = (TimePicker) dialog.findViewById(R.id.timePickerDialog);

    if(DateFormat.is24HourFormat(getActivity()){
        timePicker.setIs24HourView(true);
    }else {
        timePicker.setIs24HourView(false);
    }
    // here you can define your hour and minute value.
    timePicker.setCurrentHour(hour);
    timePicker.setCurrentMinute(minute);

      

+1


source


You can try below code



     SimpleDateFormat sdf = new SimpleDateFormat("hh:ss");
    Date date = null;
    try {
        date = sdf.parse("07:00");
    } catch (ParseException e) {
    }
    Calendar c = Calendar.getInstance();
    c.setTime(date);

    TimePicker picker = new TimePicker(getApplicationContext());
    picker.setCurrentHour(c.get(Calendar.HOUR_OF_DAY));
    picker.setCurrentMinute(c.get(Calendar.MINUTE));

      

0


source







All Articles