Rahul Varma Rahul Varma - 1 month ago 8
Android Question

Displaying the Time in AM/PM format in android

I am getting the time using a time picker and displaying the time in the text view using following code...

private TimePickerDialog.OnTimeSetListener mTimeSetListener = new TimePickerDialog.OnTimeSetListener() {
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
Toast.makeText(SendMail.this, "Your Appointment time is "+hourOfDay+":"+minute, Toast.LENGTH_SHORT).show();
TextView datehid = (TextView)findViewById(R.id.timehidden);
datehid.setText(String.valueOf(hourOfDay)+ ":"+(String.valueOf(minute)));
}
};


Now, the issue is when i set the time as 8:00 pm then i get the time displayed as 20:0... I want to display the time as 8:00 pm... How can i do that???

Answer

I have done like this to achieve it.

private TimePickerDialog.OnTimeSetListener mTimeSetListener = new TimePickerDialog.OnTimeSetListener() {
    public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
        TextView datehid = (TextView)findViewById(R.id.timehidden);
        if(hourOfDay>12) {
            datehid.setText(String.valueOf(hourOfDay-12)+ ":"+(String.valueOf(minute)+"pm"));
        } else if(hourOfDay==12) {
            datehid.setText("12"+ ":"+(String.valueOf(minute)+"pm"));
        } else if(hourOfDay<12) {
            if(hourOfDay!=0) {
                datehid.setText(String.valueOf(hourOfDay) + ":" + (String.valueOf(minute) + "am"));
            } else {
                datehid.setText("12" + ":" + (String.valueOf(minute) + "am"));
            }
        }
    }
};