currently I have a TimePickerDialog where the user will select the time and the time will be passed into an object's parameters to create a row in my SQLite database. I want to store the time as 24 hour in the database, but I want it to be displayed to the user in 12 hour format. This is my TimePickerDialog code:
TimePickerDialog.OnTimeSetListener time = new
TimePickerDialog.OnTimeSetListener() {
@Override
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
if (hourOfDay < 10) {
hourString = "0"
+ hourOfDay;
} else {
hourString = String.valueOf(hourOfDay);
}
if (minute < 10) {
minuteString = "0" + minute;
} else {
minuteString = String.valueOf(minute);
}
String twentyFourTime = hourString + ":" + minuteString;
tvScheduleTime.setText(twentyFourTime);
}
};
Then on my onCreate method, I get the time from tvScheduleTime
to save in the database
btnSaveSchedule.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// schedule items
String scheduleName = etScheduleName.getText().toString();
String scheduleDesc = etScheduleDesc.getText().toString();
String scheduleDate = Day + " " + selectedMonth + " " + Year;
String scheduleTime = tvScheduleTime.getText().toString();
int routeID = 12345;
Log.w("RESULTS", scheduleTime + scheduleDate);
DatabaseScheduleHelper db = new DatabaseScheduleHelper(getApplicationContext());
db.addSchedule(new ObjectSchedule(scheduleTime, scheduleDate, scheduleName, scheduleDesc, routeID));
}
});
Essentially, my question is, I want the scheduleTime
to be passed in the ObjectSchedule
object to be in 24 hour format and but for the text in tvScheduleTime
to be in 12 hour format . But how can I return the value of twentyFourTime
from the TimePickerDialog listener to my onCreate method? Then from there I will be able to do all my conversions.
If I get this right you just want a method to convert military time to normal time immediately when you get it (get it through DB or through OnTimeSetListener)? If so the method below should work (not tested).
int hr =
grab from DB or from TimeListener
hr = convertToNormalTime(hr);
private int convertToNormalTime(int militaryTime){
int hr = militaryTime;
if(hr > 12){
hr = militaryTime - 12; // to convert military to normal time always subtract by 12
}
return hr;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.