TimePickerDialog和AM或PM

时间:2010-04-17 20:33:08

标签: android timepicker

我有一个将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
    }
};

24 个答案:

答案 0 :(得分:62)

hourOfDay将始终为24小时。如果您打开is24HourView设置为false的对话框,则用户无需处理24小时格式化的时间,但Android会将其转换为24小时时调用{{1} }}

答案 1 :(得分:31)

这对我有用:

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

答案 2 :(得分: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

答案 3 :(得分:10)

用一个用户选择显示正确的HH:MM格式

的整洁的toast消息
    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();
    }

答案 4 :(得分:9)

我遇到了同样的问题。我的应用程序中有一个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值。

答案 5 :(得分:9)

尝试这个简单的方法:

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

答案 6 :(得分:5)

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

答案 7 :(得分:2)

试试这个:

$('#select').click(function() {
  var selectedName = $('select[name="docsApp.options"] option:selected').text();

  if ($('#select option:selected').val() == 'Herr')

  {
    $("#Herr").prop("checked", true)
  } else {
    $("#Frau").prop("checked", true)
  }

答案 8 :(得分:2)

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

sref_Time3是安培值; sref_Time1是小时组件。

$('select[name^="alphabet"] option[value='+alphabet+']').attr("selected", "selected");

谢谢&amp;问候。

Screen Time Picker Dialog

答案 9 :(得分:1)

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

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

答案 10 :(得分:1)

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

答案 11 :(得分: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);

答案 12 :(得分:0)

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

答案 13 :(得分: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();
        }
    });

答案 14 :(得分:0)

尝试一下,希望对您有帮助

result = [r[0] for r in cur.fetchall()]

答案 15 :(得分: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);

答案 16 :(得分:0)

此方法使用现有的格式功能,并且根据timePickerDialog是否在24小时支持下打开来确定am / pm与24h格式之间的关系。 Kotlin的例子。

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)

答案 17 :(得分: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());}

答案 18 :(得分:0)

无论您将is24Hour设置为false还是true,您始终会根据“ onTimeSet()”方法中的24小时格式收到“ hourOfDay”。 例如:-如果将“ is24Hour”设置为false并选择晚上8点,则“ onTimeSet()”方法中的“ hourOfDay”的值将为20。 然后可以这样设置Your 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);

        }

答案 19 :(得分:0)

这是获取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();

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

答案 20 :(得分:0)

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

答案 21 :(得分: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"
        }

答案 22 :(得分: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()

答案 23 :(得分:0)

这是 TimePicker 的一个工作示例,它已从系统默认值 (24h) 转换为(上午和下午的 12 小时),并且我已将其影响到我的 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()}');
    });
},