开发者

TimePickerDialog and AM or PM

I have a TimePickerDialog with is24Hour set to false since I want to present the end-user with the more familiar 12 hour format. When the hour, minute and AM PM indicator are set and the time is returned how can I identify whether the end-user has selected AM or PM?

This is what I have for the listener:

private TimePickerDialog.OnTimeSetListener mTimeSetListener =
      new TimePickerDialog.OnTimeSetListener() {

    @Override
    public void onTimeSet(TimePicker view, int 开发者_如何学ChourOfDay, 
      int minute) {
     mHour = hourOfDay;
     mMinute = minute;
    // mIsAM = WHERE CAN I GET THIS VALUE
    }
};


The hourOfDay will always be 24-hour. If you opened the dialog with is24HourView set to false, the user will not have to deal with 24-hour formatted times, but Android will convert that to a 24-hour time when it calls onTimeSet().


This worked for me:

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":datetime.get(Calendar.HOUR)+""; 

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


I was running into the same problem. I have a TimePicker in my app where after you choose a time and hit a button you'll be taken to a screen that showed what time was chosen. The "time" chosen was correct but sometimes the AM/PM value would be opposite of what was chosen. I finally fixed it by changing what I was storing for the "hrs" argument from the TimePicker.

private TimePickerDialog.OnTimeSetListener mTimeSetListener = new TimePickerDialog.OnTimeSetListener() 
{   
    @Override
    public void onTimeSet(TimePicker view, int hrs, int mins)
    {
        hour = hrs;
        minute = mins;

        c = Calendar.getInstance();
        c.set(Calendar.HOUR_OF_DAY, hour);
        //instead of c.set(Calendar.HOUR, hour);
        c.set(Calendar.MINUTE, minute);

Now when I hit the button to go to the next screen it properly showed the correct AM/PM value chosen.


a neat toast message with what user selected showing proper HH:MM format

    public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
        String AM_PM = " AM";
        String mm_precede = "";
        if (hourOfDay >= 12) {
            AM_PM = " PM";
            if (hourOfDay >=13 && hourOfDay < 24) {
                hourOfDay -= 12;
            }
            else {
                hourOfDay = 12;
            }
        } else if (hourOfDay == 0) {
            hourOfDay = 12;
        }
        if (minute < 10) {
            mm_precede = "0";
        }
        Toast.makeText(mContext, "" + hourOfDay + ":" + mm_precede + minute + AM_PM, Toast.LENGTH_SHORT).show();
    }


Try this simple method:

 void openTimeFragment() {
        TimePickerDialog mTimePicker;

        final Calendar c = Calendar.getInstance();
        int hour = c.get(Calendar.HOUR_OF_DAY);
        int minute = c.get(Calendar.MINUTE);

        mTimePicker = new TimePickerDialog(YourActivity.this, new TimePickerDialog.OnTimeSetListener() {
            @Override
            public void onTimeSet(TimePicker timePicker, int selectedHour, int selectedMinute) {



                String time = selectedHour + ":" + selectedMinute;

                  SimpleDateFormat fmt = new SimpleDateFormat("HH:mm");
        Date date = null;
        try {
            date = fmt.parse(time );
        } catch (ParseException e) {

            e.printStackTrace();
        }

        SimpleDateFormat fmtOut = new SimpleDateFormat("hh:mm aa");

          String formattedTime=fmtOut.format(date);

                edtTextTime.setText(formattedTime);
            }
        }, hour, minute, false);//No 24 hour time
        mTimePicker.setTitle("Select Time");
        mTimePicker.show();
    }


 private String getTime(int hr,int min) {
        Calendar cal = Calendar.getInstance();
        cal.set(Calendar.HOUR_OF_DAY,hr);
        cal.set(Calendar.MINUTE,min);
        Format formatter;
        formatter = new SimpleDateFormat("h:mm a");
        return formatter.format(cal.getTime());
    }


Hi you could use your own format like this :

    String myFormat = "hh:mm a"; // your own format
    SimpleDateFormat sdf = new SimpleDateFormat(myFormat, Locale.US);
    String  formated_time = sdf.format(calendar_time.getTime()); //format your time

I found that "a" is the code in formating time that represents AM-PM: http://www.tutorialspoint.com/java/java_date_time.htm


If your expectation was to directly set AM/PM in the Time Picker Dialog box, there is a work around. This works if you pre-populate the EditText with current/default time. - Before instantiating the dialog, increase the hour component by 12 if EditText has PM time value.

sref_Time3 is ampm value; sref_Time1 is hour component.

    if (sref_Time3.equals("PM")) {
        hour = hour + 12;
    } else if (sref_Time1.equals("12")) {
        hour = 0;
    }
    // Create a new instance of TimePickerDialog and return it
    return new TimePickerDialog(getActivity(), this, hour, minute,
               DateFormat.is24HourFormat(getActivity()));

Thanks & Regards.

TimePickerDialog and AM or PM

TimePickerDialog and AM or PM


Try this :

        Calendar calendar = Calendar.getInstance();
        calendar.set(0, 0, 0, hourOfDay, minute, 0);
        long timeInMillis = calendar.getTimeInMillis();
        java.text.DateFormat dateFormatter = new SimpleDateFormat("hh:mm a");
        Date date = new Date();
        date.setTime(timeInMillis);
        time.setText(dateFormatter.format(date));


public static class TimePickerFragment extends DialogFragment
        implements TimePickerDialog.OnTimeSetListener {

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        // Use the current time as the default values for the picker
        final Calendar c = Calendar.getInstance();
        int hour = c.get(Calendar.HOUR);
        int minute = c.get(Calendar.MINUTE);

        // Create a new instance of TimePickerDialog and return it
        return new TimePickerDialog(getActivity(), this, hour, minute,
                DateFormat.is24HourFormat(getActivity()));
    }

    public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
        Calendar calendar = Calendar.getInstance();
        calendar.set(0, 0, 0, hourOfDay, minute);
        textView.setText((String) DateFormat.format("hh:mm aaa", calendar));
    }
}


//For showing the dialog put below two lines where you want to call

TimePickerFragment timePickerFragment = new TimePickerFragment();
timePickerFragment.show(getSupportFragmentManager(), "TimePicker");


This works for me :

TimePickerDialog timePickerDialog = new TimePickerDialog(AddFocusActivity.this, new TimePickerDialog.OnTimeSetListener() {
        @Override
        public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
            calendar.set(Calendar.MINUTE, minute);
            calendar.set(Calendar.HOUR,hourOfDay);
            time = calendar.get(Calendar.HOUR)
                    + ((calendar.get(Calendar.AM_PM) == Calendar.AM) ? "am" : "pm");

            Log.e("time",time);

        }
    },calendar.get(Calendar.HOUR_OF_DAY),calendar.get(Calendar.MINUTE), false);


private TimePickerDialog.OnTimeSetListener timeSetListener = new TimePickerDialog.OnTimeSetListener() {
        @Override
        public void onTimeSet(TimePicker view, int hourOfDay, int minute) {    
            boolean isPM = (hourOfDay >= 12);
            tvTime.setText(String.format("%02d:%02d %s", (hourOfDay == 12 || hourOfDay == 0) ? 12 : hourOfDay % 12, minute, isPM ? "PM" : "AM"));
        }
    };


You can try my solution, I used "hh:mm a" format to set AM/PM time:

SimpleDateFormat formatter = new SimpleDateFormat("hh:mm a", Locale.ENGLISH);
String  formattedTime = formatter.format(myCalendar.getTime()); 
EditText.setText(formattedTime);


Try this, Hope it will help you

 int mHour;
 int mMin;
 StringBuilder stringBuilder = new StringBuilder();

 TimePickerDialog timePickerDialog = new TimePickerDialog(context, new  
 TimePickerDialog.OnTimeSetListener() {

        @Override
        public void onTimeSet(TimePicker view, int hourOfDay, int minute) {

            mHour = hourOfDay;
            mMin = minute;

            String am_pm ;

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

            am_pm = getTime(mHour,mMin);

            stringBuilder.append(" ");
            stringBuilder.append(am_pm);
            editTextDate.setText(stringBuilder);

        }

    }, mHour, mMin, false);

    timePickerDialog.show();



 public String getTime(int hr, int min) {
    Calendar cal = Calendar.getInstance();
    cal.set(Calendar.HOUR_OF_DAY,hr);
    cal.set(Calendar.MINUTE,min);
    Format formatter;
    formatter = new SimpleDateFormat("h:mm a");
    return formatter.format(cal.getTime());
}


I know it's too late for answer, and perfect answer is already selected, But I thought it is not quite clear for beginners, so posting my answer

editText.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            // TODO Auto-generated method stub
            Calendar mcurrentTime = Calendar.getInstance();
            int hour = mcurrentTime.get(Calendar.HOUR_OF_DAY);
            int minute = mcurrentTime.get(Calendar.MINUTE);

            TimePickerDialog mTimePicker;
            mTimePicker = new TimePickerDialog(getActivity(), new TimePickerDialog.OnTimeSetListener() {
                @Override
                public void onTimeSet(TimePicker timePicker, int selectedHour, int selectedMinute) {
                    String AM_PM;
                    if (selectedHour >=0 && selectedHour < 12){
                        AM_PM = "AM";
                    } else {
                        AM_PM = "PM";
                    }
                    editText.setText( selectedHour + ":" + selectedMinute+" "+AM_PM);
                }
            }, hour, minute, false);
            mTimePicker.setTitle("Select Time");
            mTimePicker.show();
        }
    });


While using the TimeDialog to get the time and set it to an EditText, I have found that if the 'minutes' are less than 0, ex: 12:05, it giving like 12:5. Here in this code I've solved that issue and also properly using TimeDialog to get AM/PM if you want 12 hour format. Replace the your onTimeSet() with the following

public void onTimeSet(TimePicker timePicker, int selectedHour, int selectedMinute) {
                    String period;
                    int hour = 0;
                    String minute;
                    if(selectedMinute >= 0 && selectedMinute < 10)
                        minute = "0" + selectedMinute;
                    else
                        minute = String.valueOf(selectedMinute);
                    if(selectedHour >= 0 && selectedHour < 12)
                        period = "AM";
                    else
                        period = "PM";
                    if(period.equals("AM")){
                        if(selectedHour == 0)
                            hour = 12;
                        else if(selectedHour >= 1 && selectedHour < 12)
                            hour = selectedHour;
                    }else if(period.equals("PM")){
                        if(selectedHour == 12)
                            hour = 12;
                        else if(selectedHour >= 13 && selectedHour <= 23)
                            hour = selectedHour - 12;
                    }
                    String time = hour+":"+minute+" "+period;
                    currentText.setText(time);
                }
            }, hour, minute, false);


This approach uses existing format functionality and the decision between am/pm and 24h format is based on if the timePickerDialog was opened with 24 hours support or not. Kotlin example.

val timePickerDialog = TimePickerDialog(
    requireContext(), TimePickerDialog.OnTimeSetListener { timePicker, hourOfDay, minutes ->

        val datetime = Calendar.getInstance()
        datetime.set(Calendar.HOUR_OF_DAY, hourOfDay)
        datetime.set(Calendar.MINUTE, minutes)

        val timeFormatAmPm = SimpleDateFormat("hh:mm aa")
        val timeFormat24Hours = SimpleDateFormat("HH:mm")

        timeEditTextView.setText(
            when (timePicker.is24HourView) {
                true -> timeFormat24Hours.format(datetime.time)
                false -> timeFormatAmPm.format(datetime.time)
            }
        )
    },
    currentHour, currentMinute, is24HourFormat
)

BR Matthias


@Override
public void onTimeSet(TimePicker timePicker, int selectedHour, int selectedMinute) {
    SimpleDateFormat timeFormat = new SimpleDateFormat("h:mm a", Locale.getDefault());
Calendar mCurrentTime = Calendar.getInstance();                
mCurrentTime.set(Calendar.HOUR_OF_DAY, selectedHour);
mCurrentTime.set(Calendar.MINUTE, selectedMinute);
mCurrentTime.clear(Calendar.SECOND);
String time = timeFormat.format(mCurrentTime.getTimeInMillis());
tvTime.setText(time.toLowerCase());}


Whether you set is24Hour to false or true you always receive "hourOfDay" according to 24 hour format in "onTimeSet()" method. Ex :- if you set "is24Hour" to false and select 8 pm then the value of "hourOfDay" in "onTimeSet()" method will be 20. and then you can set Your Am and Pm like this :

 public void onTimeSet(TimePicker timePicker, int hourOfDay, int minute) {

            String minute_precede = "", hour_precede = "", finalTIme = "", amOrPm = "";
            int hourValue = 0;

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

            if (datetime.get(Calendar.AM_PM) == Calendar.AM) {
                amOrPm = "AM";
                if (hourOfDay == 0)
                    hourValue = 12;
                else
                    hourValue = hourOfDay;
            } else if (datetime.get(Calendar.AM_PM) == Calendar.PM) {
                amOrPm = "PM";
                if (hourOfDay == 12)
                    hourValue = 12;
                else if (hourOfDay >= 13 && hourOfDay <= 23)
                    hourValue = hourOfDay - 12;
            }
            if (hourValue < 10)
                hour_precede = "0";
            if (minute < 10)
                minute_precede = "0";
            finalTIme = hour_precede + hourValue + ":" + minute_precede + minute + " " + amOrPm;
            mTimeEditText.setText(finalTIme);

        }


This is the simplest method to get selected time in AM, PM

Calendar mcurrentTime = Calendar.getInstance();
            int hour = mcurrentTime.get(Calendar.HOUR_OF_DAY);
            int minute = mcurrentTime.get(Calendar.MINUTE);
            TimePickerDialog mTimePicker;
            mTimePicker = new TimePickerDialog(Quiz_Add.this, new TimePickerDialog.OnTimeSetListener() {
                @Override
                public void onTimeSet(TimePicker timePicker, int selectedHour, int selectedMinute) {
                    String strHour=String.valueOf(selectedHour), strMin=String.valueOf(selectedMinute), strAM_PM;
                    // if(strHour.length()==1) strHour="0" + strHour;
                    if(strMin.length()==1) strMin="0" + strMin;

                    if(selectedHour==0){
                        selectedHour+=12;   strAM_PM="AM";
                    }else if(selectedHour==12){
                        strAM_PM="PM";
                    }else if(selectedHour>12){
                        selectedHour=selectedHour-12;   strAM_PM="PM";
                    }else{
                        strAM_PM="AM";
                    }

                    txtTm.setText( selectedHour + ":" + strMin + " " + strAM_PM);
                }
            }, hour, minute, false);//Yes 24 hour time
            mTimePicker.setTitle("Select Time");
            mTimePicker.show();

This way you will always get the correct selected time with AM or PM


In Kotlin

        val calenderInstance = Calendar.getInstance()
        val hr = calenderInstance[Calendar.HOUR_OF_DAY]
        val min = calenderInstance[Calendar.MINUTE]
        val onTimeListner =
            OnTimeSetListener { view, hourOfDay, minute ->
                if (view.isShown) {
                    calenderInstance[Calendar.HOUR_OF_DAY] = hourOfDay
                    calenderInstance[Calendar.MINUTE] = minute

                    Log.e("@@time",hourOfDay.toString()+" "+minute.toString())
                }
            }
        val timePickerDialog = TimePickerDialog(
            this@BlockDateActivity,
            android.R.style.Theme_Holo_Light_Dialog_NoActionBar,
            onTimeListner, hr, min, false
        )
          timePickerDialog.setTitle("Set Time")
        Objects.requireNonNull(timePickerDialog.window)!!
            .setBackgroundDrawableResource(android.R.color.transparent)
        timePickerDialog.show()


here is a simple timePickerUtil:

class TimePickerHelper(
    val context: Context,
    private val inputTime: String,
    val callback: (time: String) -> Unit
) {
    fun showPicker() {
        var hour = 0
        var minute = 0
        val formattedInputTime = covertDate(
            inputTime,
            Constants.DateFormats.HH_MM_A,
            Constants.DateFormats.HH_MM
        )
        if (formattedInputTime.isNotEmpty()) {
            val arr = formattedInputTime.split(":")
            hour = arr[0].toInt()
            minute = arr[1].toInt()
        }
        val timePickerDialog = TimePickerDialog(
            context,
            { view, h, m ->
                callback(
                    covertDate(
                        "$h:$m",
                        Constants.DateFormats.HH_MM,
                        Constants.DateFormats.HH_MM_A
                    )
                )
            },
            hour,
            minute,
            false
        )
        timePickerDialog.show()
    }

}



@SuppressLint("SimpleDateFormat")
fun covertDate(date: String, inputFormat: String, outputFormat: String): String {
    var formattedDate = ""
    try {
        val dateObject =
            SimpleDateFormat(inputFormat).parse(date)
        formattedDate = SimpleDateFormat(outputFormat).format(dateObject)
    } catch (e: Exception) {
        Timber.e(e)
    }

    return formattedDate
}

//Belongs to Constants class
    object DateFormats {
            const val TIME_STAMP_WITH_ZONE: String = "yyyy-MM-dd'T'HH:mm:ss.s"
            const val MMM_YYYY: String = "MMM YYYY"
            const val DD_MM_YY: String = "dd/MM/yy"
            const val HH_MM_A: String = "hh:mm aa"
            const val HH_MM: String = "HH:mm"
        }


The Following Code in Kotlin is very Simple and Easy. A common mistake everyone make is shown with ** Sign.

        val cal = Calendar.getInstance()
        val timeSetListner = TimePickerDialog.OnTimeSetListener { view, hourOfDay, minute ->
            cal.set(Calendar.HOUR_OF_DAY,hourOfDay)
            cal.set(Calendar.MINUTE,minute)

            var am_or_pm : String = ""
            if (hourOfDay>12) {
                am_or_pm = "PM"
            }

            else {
                am_or_pm = "AM"
            }
            
            **//In Below Code Time Format Should be in small letters ie, hh:mm
            **//If enter HH:mm the result will be wrong

            val text = SimpleDateFormat("hh:mm").format(cal.time)
            binding.wakeupTimeChangeText.setText(text+ am_or_pm)
        }
        TimePickerDialog(requireContext(),timeSetListner,cal.get(Calendar.HOUR_OF_DAY),cal.get(Calendar.MINUTE),false)
            .show()


This is a working example of the TimePicker that has been transformed from system default (24h) to (12h with AM and PM) and I have affected that to my FormField:

onTap: () {

    showTimePicker(builder: (context, childWidget) {
            return MediaQuery(
                data: MediaQuery.of(context).copyWith(
                    // Using 24-Hour format
                    alwaysUse24HourFormat: false),
                // If you want 12-Hour format, just change alwaysUse24HourFormat to false or remove all the builder argument
                child: childWidget!);
        },
        context: context,
        initialTime: TimeOfDay.now()
    ).then((value) {
        if (value != null) {
            if (value.period == DayPeriod.am) {
                timeController.text = value.format(context) + " AM";
            } else {
                timeController.text = value.format(context) + " PM";
            }

        }

    }).catchError((error) {
        print('the Error is : ${error.toString()}');
    });
},


    private void OnTimeSet(object sender, TimePickerDialog.TimeSetEventArgs e)
    {
        if (e.HourOfDay == 0)
        {

            hour += 12;
            format = "AM";
            Hour = (e.HourOfDay + 12).ToString();
        }
        else if (e.HourOfDay == 12)
        {
            format = "PM";
            Hour = (e.HourOfDay).ToString();
        }
        else if (e.HourOfDay > 12)
        {
            hour -= 12;
            format = "PM";
            Hour = (e.HourOfDay - 12).ToString();
        }
        else
        {
            format = "AM";
            Hour = (e.HourOfDay).ToString();
        }
        minute = e.Minute;
        string selectedTime = ("" + Hour.ToString().PadLeft(2, '0') + ":" + 
        minute.ToString().PadLeft(2, '0') + " " + format);
        LatestTime.Text = selectedTime;
    }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜