Android: Setting time in time picker with the time shown in text view
You should use a SimpleDateFormat
to get a Date
object from your String
.
Then just call
picker.setCurrentHour(date.getHours())
and
picker.setCurrentMinute(date.getMinutes())
Since the Date
object is deprecated, you should use a Calendar
instead of it.
You can instantiate a Calendar
this way:
Calendar c = Calendar.getInstance();
c.setTime(date);
picker.setCurrentHour(c.get(Calendar.HOUR_OF_DAY));
picker.setCurrentMinute(c.get(Calendat.MINUTE));
Edit: the complete code:
import java.util.Date;
import java.text.SimpleDateFormat; //Don't use "android.icu.text.SimpleDateFormat"
import java.text.ParseException; //Don't use "android.net.ParseException"
SimpleDateFormat sdf = new SimpleDateFormat("hh:mm");
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));
If anybody using the following format that is without using timepicker widget use this one..
mStartTime.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
new TimePickerDialog(AddAppointmentActivity.this, onStartTimeListener, calendar
.get(Calendar.HOUR), calendar.get(Calendar.MINUTE), false).show();
}
});
TimePickerDialog.OnTimeSetListener onStartTimeListener = new OnTimeSetListener() {
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
String AM_PM;
int am_pm;
mStartTime.setText(hourOfDay + " : " + minute + " " + AM_PM);
calendar.set(Calendar.HOUR, hourOfDay);
calendar.set(Calendar.MINUTE, minute);
}
};