60

我有一个将 is24Hour 设置为 false 的 TimePickerDialog,因为我想向最终用户展示更熟悉的 12 小时格式。当设置小时、分钟和 AM PM 指示器并返回时间时,如何识别最终用户选择的是 AM 还是 PM?

这就是我为听众准备的:

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

    @Override
    public void onTimeSet(TimePicker view, int hourOfDay, 
      int minute) {
     mHour = hourOfDay;
     mMinute = minute;
    // mIsAM = WHERE CAN I GET THIS VALUE
    }
};
4

25 回答 25

79

hourOfDay始终是 24 小时。如果您打开对话框并is24HourView设置为false,用户将不必处理 24 小时格式的时间,但 Android 会在调用 时将其转换为 24 小时时间onTimeSet()

于 2010-04-17T21:28:53.180 回答
45

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 );
}
于 2013-02-20T10:49:35.760 回答
13

我遇到了同样的问题。我的应用程序中有一个 TimePicker,在您选择时间并点击按钮后,您将被带到显示所选时间的屏幕。选择的“时间”是正确的,但有时 AM/PM 值会与选择的相反。我最终通过更改我为 TimePicker 中的“hrs”参数存储的内容来修复它。

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);

现在,当我按下按钮进入下一个屏幕时,它会正确显示选择的正确 AM/PM 值。

于 2011-12-30T19:08:53.447 回答
13

试试这个简单的方法:

 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();
    }
于 2016-09-13T13:15:36.910 回答
12

一条简洁的吐司消息,其中包含用户选择的内容,显示正确的 HH:MM 格式

    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();
    }
于 2015-08-07T00:01:41.033 回答
11
 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());
    }
于 2017-01-30T22:35:22.377 回答
10

您好,您可以像这样使用自己的格式:

    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

我发现“a”是表示 AM-PM 的格式化时间代码:http ://www.tutorialspoint.com/java/java_date_time.htm

于 2014-06-06T19:47:08.390 回答
2

如果您的期望是直接在时间选择器对话框中设置 AM/PM,则可以解决此问题。如果您使用当前/默认时间预先填充 EditText,则此方法有效。- 在实例化对话框之前,如果 EditText 具有 PM 时间值,则将小时分量增加 12。

sref_Time3 是安培值;sref_Time1 是小时分量。

    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()));

感谢和问候。

屏幕 时间选择器对话框

于 2015-10-02T08:24:44.920 回答
2
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");
于 2016-03-18T06:03:29.873 回答
2

尝试这个 :

        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));
于 2015-09-01T06:47:31.807 回答
1
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"));
        }
    };
于 2015-11-19T09:09:21.117 回答
1

您可以尝试我的解决方案,我使用“hh:mm a”格式来设置AM/PM 时间

SimpleDateFormat formatter = new SimpleDateFormat("hh:mm a", Locale.ENGLISH);
String  formattedTime = formatter.format(myCalendar.getTime()); 
EditText.setText(formattedTime);
于 2017-07-06T07:45:04.913 回答
1

试试这个,希望对你有帮助

 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());
}
于 2018-07-11T12:06:45.360 回答
1

这对我有用:

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);
于 2015-11-02T07:43:16.713 回答
0

在科特林

        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()
于 2021-01-27T11:45:17.520 回答
0

Kotlin 中的以下代码非常简单易行。每个人都会犯的一个常见错误用 ** 符号表示。

        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()
于 2021-06-16T11:48:54.400 回答
0
@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());}
于 2020-02-02T03:25:46.763 回答
0
    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;
    }
于 2022-02-01T06:47:56.713 回答
0

无论您将 is24Hour 设置为 false 还是 true,您始终会根据“onTimeSet()”方法中的 24 小时格式收到“hourOfDay”。例如:- 如果您将“is24Hour”设置为 false 并选择 8 pm,那么“onTimeSet()”方法中“hourOfDay”的值将是 20。然后您可以像这样设置您的 Am 和 Pm:

 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);

        }
于 2020-05-27T15:58:37.353 回答
0

这是在上午、下午获取选定时间的最简单方法

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();

这样,您将始终使用 AM 或 PM 获得正确的选择时间

于 2020-08-13T07:01:51.977 回答
0

在使用 TimeDialog 获取时间并将其设置为 EditText 时,我发现如果“分钟”小于 0,例如:12:05,它会给出 12:5。在这段代码中,我已经解决了这个问题,并且如果您想要 12 小时格式,还可以正确使用 TimeDialog 来获取 AM/PM。将您的 onTimeSet() 替换为以下内容

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);
于 2018-10-24T13:08:34.803 回答
0

这是一个简单的 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"
        }
于 2021-04-21T09:56:49.510 回答
0

我知道答案为时已晚,并且已经选择了完美的答案,但是我认为对于初学者来说还不是很清楚,所以发布我的答案

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();
        }
    });
于 2017-12-27T06:30:15.760 回答
0

这种方法使用现有的格式功能,上午/下午和 24 小时格式之间的决定取决于是否在timePickerDialog24 小时支持下打开。科特林的例子。

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马蒂亚斯

于 2018-11-16T15:26:59.423 回答
0

这是TimePicker已从系统默认值 (24h) 转换为 (12h with AM 和 PM) 的工作示例,我已将其影响到我的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()}');
    });
},
于 2021-08-02T15:47:59.493 回答