I just want to get the hour and the time from the TimePicker, which I'm storing as a string value. The user initially clicks an editText which will open up a TimePickerDialog. Please find the code below
initialTimeEditText.setOnClickListener(this);
public void onClick(View view) {
int mYear;
int mMonth;
int mDay;
if (view == initialTimeEditText) {
final Calendar c = Calendar.getInstance();
int mHour = c.get(Calendar.HOUR_OF_DAY);
int mMinute = c.get(Calendar.MINUTE);
// Launch Time Picker Dialog
TimePickerDialog timePickerDialog = new TimePickerDialog(this,
new TimePickerDialog.OnTimeSetListener() {
@Override
public void onTimeSet(TimePicker view, int hourOfDay,
int minute) {
String hourString;
if (hourOfDay < 10)
hourString = "0" + hourOfDay;
else
hourString = "" + hourOfDay;
String am_pm = (hourOfDay < 12) ? "AM" : "PM";
String minuteSting;
if (minute < 10)
minuteSting = "0" + minute;
else
minuteSting = "" + minute;
initialTimeEditText.setText(hourString + ":" + minuteSting + " " + am_pm);
}
}, mHour, mMinute, false);
timePickerDialog.show();
}
I have this editText named initialTimeEditText, and when I user clicks on the editText, I create a TimePickerDialog. When I am storing the value into the database, I store it as a String. You can see in the code where I setText to the EditText as a String value. This is how I store it in Firebase database
String initialTime = initialTimeEditText.getText().toString().trim();
medicationsMap.put("initialTime", initialTime);
My question is, I have this value initialTime which is a String and I want to extract the hour and minute value and set it to the calendar instance like
Calendar calendar = Calendar.getInstance(),
calendar.set(Calendar.HOUR_OF_DAY, timePickerDialog.getHour());
The code mentioned above is totally a different method. I just have access to the initialTime String value. Can I get the hour and minute value from that String?
Can this be done? If so, any way to do it? Kindly help.
Try
String[] timeArray = initialTime.split(":");
if(timeArray.length > 0) {
int hours = Integer.parseInt(timeArray[0]);
String[] array2 = timeArray[1].split(" ");
int minutes = Integer.parseInt(array2[0]);
String amPm = array2[1];
Calendar calendar = Calendar.getInstance(),
calendar.set(Calendar.HOUR_OF_DAY, hours);
calendar.set(Calendar.MINUTE, minutes);
}