I am planning to add an hour to the current time, which I have converted into a 12 hour format. Just not sure how to go about it. I want to keep mins the same, just want to add an hour, say the time is 11:59am -> I would like to show 12:59pm, or if the time is 5:20, I would like to show 6:20 and so on. Here's my code so far :
if (mDate.get(Calendar.AM_PM) == Calendar.AM)
am_pm = "AM";
else if (mDate.get(Calendar.AM_PM) == Calendar.PM)
am_pm = "PM";
String strHrsToShow = (mDate.get(Calendar.HOUR) == 0) ? "12" : mDate.get(Calendar.HOUR) + "";
String strMinsToShow = (mDate.get(Calendar.MINUTE)) < 10 ? "0" + mDate.get(Calendar.MINUTE) : "" + mDate.get(Calendar.MINUTE);
mRegisterGuestStartTime.setText(String.format("%s:%s %s", strHrsToShow, strMinsToShow, am_pm));
Any ideas how to go about it? thanks in advance!
mDate
is a Calendar
object I assume. If yes, why don't you use Calendar.add(Calendar.HOUR, 1)
? Doing it in String manipulation way lost the precision of the date/time value. You can use SimpleDateFormat
to format the Calendar afterward
// add an hour to the date
mDate.add(Calendar.HOUR, 1);
// prepare datetime formatter, sample output: "11:35 AM"
SimpleDateFormat timeFormat = new SimpleDateFormat("HH:mm a");
mRegisterGuestStartTime.setText(timeFormat.format(mDate.getTime()));