我将24小时格式转换为12小时格式时遇到问题.这是我的代码.
private TimePickerDialog.OnTimeSetListener mTimeSetListener = new TimePickerDialog.OnTimeSetListener() { @Override public void onTimeSet(TimePicker view,int hourOfDay,int minute) { // TODO Auto-generated method stub ViewGroup vg=(ViewGroup) view.getChildAt(0); hour = hourOfDay; minutes = minute; String am_pm = (hourOfDay < 12) ? "AM" : "PM"; SimpleDateFormat sdf = new SimpleDateFormat("hh:mm a",Locale.US); String tme = hour +":"+ minutes+am_pm; et1.setText(tme); } };
我从警报对话框切换到timepicker对话框,因为我不知道如何将24小时更改为12小时格式
et1.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub new TimePickerDialog(MainActivity.this,mTimeSetListener,hour,minutes,false).show(); } }); }
这证明我已经将布尔印象变为false.
解决方法
试试这个-
private TimePickerDialog.OnTimeSetListener mTimeSetListener = new TimePickerDialog.OnTimeSetListener() { @Override public void onTimeSet(TimePicker view,int minute) { // TODO Auto-generated method stub hour = hourOfDay; minutes = minute; String timeSet = ""; if (hour > 12) { hour -= 12; timeSet = "PM"; } else if (hour == 0) { hour += 12; timeSet = "AM"; } else if (hour == 12){ timeSet = "PM"; }else{ timeSet = "AM"; } String min = ""; if (minutes < 10) min = "0" + minutes ; else min = String.valueOf(minutes); // Append in a StringBuilder String aTime = new StringBuilder().append(hour).append(':') .append(min ).append(" ").append(timeSet).toString(); et1.setText(aTime); } };