I have a problem displaying the correct AM/PM of a calculated sleep cycle of a person. For example, the user clicks his waking time at 7:00 AM, the app should return the sleeping time at 11:15 PM. In my app, it’s displaying 11:15 AM not PM.
Can you help me with what I have tried so far:
private TimePickerDialog.OnTimeSetListener timePickerListener =
new TimePickerDialog.OnTimeSetListener() {
public void onTimeSet( TimePicker view, int selectedHour,
int selectedMinute ) {
// Gets current time
Calendar c = Calendar.getInstance();
hour = selectedHour;
minute = selectedMinute;
// set waking time into textview
StringBuilder sb = new StringBuilder();
if(hour>=12){
sb.append(hour-12).append( ":" ).append(minute).append(" PM");
}else{
sb.append(hour).append( ":" ).append(minute).append(" AM");
}
wakingtime.setText(sb);
// Assign hour set in the picker
c.set( Calendar.HOUR, selectedHour );
c.set( Calendar.MINUTE, selectedMinute );
// Have Calendar calculate the substraction of hours and minutes
c.add( Calendar.HOUR, SUB_HOUR );
c.add( Calendar.MINUTE, SUB_MINUTE );
// Get the hour and the minute calculated
hour = c.get( Calendar.HOUR );
minute = c.get( Calendar.MINUTE );
StringBuilder sb2 = new StringBuilder();
if(hour>=12){
sb2.append(hour-12).append( ":" ).append(minute).append(" PM");
}else{
sb2.append(hour).append( ":" ).append(minute).append(" AM");
}
answer.setText(sb2);
// set current time into textview
//answer.setText( "You must go to bed at " + new StringBuilder().append(pad(hour))
// .append(":").append(pad(minute)) );
}
};
Any help is truly appreciated! Thanks.
Refer to the small discussion with @Simon above in the comments, the Calendar variable you want to set is Calendar.HOUR_OF_DAY. Here is what you’re setting, and getting. You want the one that’s below that.