32

I want to set an alarm based on a user's selection in TimePicker. TimePicker is set to AM/PM mode. In order to know if a user wants his alarm to set to 10 AM or 10 PM, how should I get the AM/PM value?

The listener TimePickerDialog.OnTimeSetListener passes only hours and minutes.

sandalone
  • 41,141
  • 63
  • 222
  • 338

9 Answers9

36

Above answers are right i found simplest way to find AM PM.

TimePickerDialog.OnTimeSetListener onStartTimeListener = new OnTimeSetListener() {

    public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
        String AM_PM ;
        if(hourOfDay < 12) {
            AM_PM = "AM";
        } else {
            AM_PM = "PM";
        }

        mStartTime.setText(hourOfDay + " : " + minute + " " + AM_PM );
    }
};
Aravin
  • 4,126
  • 1
  • 23
  • 39
  • 8
    If the time format is in 24hours, why do we need AM_PM? Is there any other way to get AM_PM in 12 hours format? – Simon Aug 29 '17 at 16:15
21

On callback from

public void onTimeSet(TimePicker view, int hourOfDay, int minute) 

call below function

private String getTime(int hr,int min) {
        Time tme = new Time(hr,min,0);//seconds by default set to zero
        Format formatter;
        formatter = new SimpleDateFormat("h:mm a");
        return formatter.format(tme);
    }

The functions return something like this 1:12 PM

Basavaraj Hampali
  • 3,905
  • 1
  • 19
  • 22
  • Time class is deprecated, please use code below to formate the time `SimpleDateFormat timeFormat = new SimpleDateFormat("HH:mm a",Locale.getDefault()); Calenter calendar = Calendar.getInstance(); calendar.set(Calendar.HOUR_OF_DAY, tp.getCurrentHour()); calendar.set(Calendar.MINUTE, tp.setCurrentMinutes()); calendar.clear(Calendar.SECOND); timeFormat.format(calendar.getTime);` – Bhavin Desai Sep 25 '19 at 05:19
12

You can get AM/PM from Timepicker using following method. Timepicker is a viewgroup.That's why we can get its child view index 2 which demonstrates AM/PM is actually a button. So we can get its text.

 Mycallback=new OnTimeSetListener() {

        public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
        ViewGroup vg=(ViewGroup) view.getChildAt(0);
            Toast.makeText(TimePickerDemoActivity.this, hourOfDay+":"+minute+":"+((Button)vg.getChildAt(2)).getText().toString(), 5000).show();

        }
    };
Bharat
  • 121
  • 1
  • 6
12

I would've preferred to leave this as a comment, but I don't have enough reputation. By far the most succinct way to get AM or PM is using the ternary operator:

String am_pm = (hourOfDay < 12) ? "AM" : "PM";
Mack
  • 2,614
  • 2
  • 21
  • 33
  • but what should one do if you are in am-pm mode... is24HourView() returns false. http://developer.android.com/reference/android/widget/TimePicker.html#is24HourView() – likejudo Feb 09 '14 at 14:43
  • [Same thing](http://stackoverflow.com/questions/2659954/timepickerdialog-and-am-or-pm/2660148#2660148) – Mack Feb 10 '14 at 15:51
5

I did it using Calendar, and that should work on all versions:

public void onTimeSet(TimePicker view, int hourOfDay, int minute){
    String am_pm = "";

    Calendar datetime = Calendar.getInstance();
    datetime.set(Calendar.HOUR_OF_DAY, hourOfDay);
    datetime.set(Calendar.MINUTE, minute);

    if (datetime.get(Calendar.AM_PM) == Calendar.AM)
        am_pm = "AM";
    else if (datetime.get(Calendar.AM_PM) == Calendar.PM)
        am_pm = "PM";

    String strHrsToShow = (datetime.get(Calendar.HOUR) == 0) ?"12":Integer.toString( datetime.get(Calendar.HOUR) );


    ((Button)getActivity().findViewById(R.id.btnEventStartTime)).setText( strHrsToShow+":"+datetime.get(Calendar.MINUTE)+" "+am_pm );
}

Notice the use of Calendar.HOUR_OF_DAY and Calendar.HOUR if you go to the documentation of both you'd know the trick.

Adil Malik
  • 6,279
  • 7
  • 48
  • 77
5

Here I'm taking the current date and time from the system and updating it with date and time picker dialog

private int  mMonth,mYear,mDay,mHour,mMin;

public static final int DTPKR = 1;

public static final int TMPKR = 2;

// Getting  the current date and time into DatePicker dialog

    public void getCurrentDate(){
       final Calendar c = Calendar.getInstance();
        mYear = c.get(Calendar.YEAR);
        mMonth = c.get(Calendar.MONTH);
        mDay = c.get(Calendar.DAY_OF_MONTH);
    } 

    public void getCurrentTime(){
                final Calendar c = Calendar.getInstance();
            mHour = c.get(Calendar.HOUR_OF_DAY);
            mMin = c.get(Calendar.MINUTE);

      } 

Now create the dialogs and update the values //Creating dialogs

    protected Dialog onCreateDialog(int id) {
        switch (id) {
        case DTPKR:
            return new DatePickerDialog(this,lisDate, mYear, mMonth, mDay);
        case TMPKR:
            return new TimePickerDialog(this,lisTime,mHour, mMin, false);
        }
        return null;
    }

    //setting date and updating editText 

       DatePickerDialog.OnDateSetListener lisDate = new DatePickerDialog.OnDateSetListener() {
               @Override
               public void onDateSet(DatePicker view, int year, int monthOfYear,
                 int dayOfMonth) {
                   mYear = year;
                    mMonth = monthOfYear;
                    mDay = dayOfMonth;
                etDate.setText(new StringBuilder() .append(mDay).append("/").append(mMonth+1).append("/").append(mYear));
                getCurrentDate();     

             }
    };

  //setting time and updating editText 

    TimePickerDialog.OnTimeSetListener lisTime=new TimePickerDialog.OnTimeSetListener() {

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

             String AM_PM ;
                if(hourOfDay < 12) {
                    AM_PM = "AM";

                } else {
                    AM_PM = "PM";
                    mHour=mHour-12;
                }
                etTime.setText(mHour+":"+mMin+" "+AM_PM);
                getCurrentDate();
        }
    };
duggu
  • 37,851
  • 12
  • 116
  • 113
Mukesh
  • 266
  • 1
  • 4
  • 10
2

Not sure if it'll help but I am kind of working on the same thing. See my reply here TimePickerDialog and AM or PM

Community
  • 1
  • 1
joelreeves
  • 1,955
  • 1
  • 18
  • 24
1

I think callback will be called with hour in 24-format because. Dialog uses TimePicker internally. And TimePicker has getCurrentHour moethod, which returns hour in 0-23 format.

Mikita Belahlazau
  • 15,326
  • 2
  • 38
  • 43
0

e.g :

TimePicker sellerTime = (TimePicker) findViewById(R.id.sellerTime);

Integer.toString(((sellerTime.getCurrentHour().intValue()) > 12) ?  ((sellerTime.getCurrentHour().intValue()) - 12) : 
(sellerTime.getCurrentHour().intValue())
duggu
  • 37,851
  • 12
  • 116
  • 113
Santosh
  • 27
  • 5