Search code examples
androidtimedialogpickerzone

How do I change Time zone in android?


I have an edit text with time picker. When I clicked on the edit text getting time picker dialog. If I select 10:00 PM edit text should display 10:00 PM, but I m getting 22:00 PM. How can I change this? My coding part given below..

 protected void showTime() 
 {
    TimePickerDialog tpd = new TimePickerDialog(this,
            new TimePickerDialog.OnTimeSetListener() 
    {

                @Override
                public void onTimeSet(TimePicker view, int hourOfDay,
                        int minute)
                {
                    hour=hourOfDay;
                    min=minute;

                    if(hourOfDay>12)
                    {
                        hourOfDay -= 12;
                        zone = "PM";
                    }
                    else
                    {
                        zone = "AM";
                    }
                    edtTime.setText(" "+pad(hour) + ":" + min+ " "+zone);
                }
            }, hour, min, true);
    tpd.setTitle("Select Time");
    tpd.show();

}

Solution

  • Notice that you're only modifying hourOfDay as hourOfDay -= 12; Hence, you need to use the same variable in your setText() call as well because hour still refers to the original 24-hour format value.

    @Override
    public void onTimeSet(TimePicker view, int hourOfDay,
            int minute)
    {
        hour=hourOfDay;
        min=minute;
    
        if(hourOfDay>12)
        {
            hourOfDay -= 12;
            zone = "PM";
        }
        else
        {
            zone = "AM";
        }
        edtTime.setText(" "+pad(hourOfDay) + ":" + min+ " "+zone);
    }
    

    Please, use the Java DateTime API instead of employing mathematics to convert from the 24-hour format (that the onTimeSet() parameters come in) to the AM/PM one. The edge cases (like 00:00) are harder to display otherwise. Here's how I would suggest you to do it.

    DateFormat df = new SimpleDateFormat("hh:mm a"); // [1-12]:[0-59] AM|PM
    
    Calendar cal = Calendar.getInstance();
    cal.set(Calendar.MINUTE, minute);
    cal.set(Calendar.HOUR_OF_DAY, hourOfDay);
    
    edtTime.setText(df.format(cal.getTime()));
    

    Check out the SimpleDateFormat docs for more info.