我只想从TimePicker获取时间和时间,我将其存储为字符串值。用户最初单击editText,这将打开TimePickerDialog。请找到以下代码
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();
}
我有一个名为initialTimeEditText的editText,当我用户点击editText时,我创建了一个TimePickerDialog。当我将值存储到数据库中时,我将其存储为String。您可以在代码中看到我将setText作为String值的EditText。这就是我将其存储在Firebase数据库中的方式
String initialTime = initialTimeEditText.getText().toString().trim();
medicationsMap.put("initialTime", initialTime);
我的问题是,我有这个值initialTime是一个字符串,我想提取小时和分钟值并将其设置为日历实例,如
Calendar calendar = Calendar.getInstance(),
calendar.set(Calendar.HOUR_OF_DAY, timePickerDialog.getHour());
上面提到的代码完全是另一种方法。我只能访问initialTime字符串值。我可以从该字符串中获取小时和分钟值吗?
可以这样做吗?如果是这样,有什么办法吗?请帮助。
答案 0 :(得分:1)
尝试
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);
}
答案 1 :(得分:1)
我只想从TimePicker获取时间和时间,我将其存储为字符串值。用户最初单击editText,这将打开TimePickerDialog。请找到以下代码
我使用Stringtokenizer来分隔小时和分钟
StringTokenizer st = new StringTokenizer(holder.mTitle.getText().toString().trim(), ":");
while (st.hasMoreElements()) {
String hourOfDay = st.nextElement().toString();
String minute = st.nextElement().toString();
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, Integer.parseInt(hourOfDay));
calendar.set(Calendar.MINUTE, Integer.parseInt(minute));
calendar.set(Calendar.SECOND, 0);
}