您好我想在Android中将24小时转换为12小时。时间来自timepicker对话框中的用户输入,然后在textview中显示。如果用户单击选择器对话框中的PM按钮,它应自动在文本视图中显示该按钮。例如,用户点击凌晨3点,它应该在文本视图中显示为凌晨3点,而另一个用户点击下午3点,它应该在文本视图中显示在下午3点而不是15点。有什么帮助吗?
请检查我下面的代码:
public void onTimeSet( TimePicker view, int selectedHour,
int selectedMinute ) {
// Gets current time
Calendar c = Calendar.getInstance();
hour = selectedHour;
minute = selectedMinute;
// set waking time into textview
String getWT = wakingtime.getText().toString();
wakingtime.setText( new StringBuilder().append( pad( hour ))
.append( ":" ).append( pad( minute )));
// Assign hour set in the picker
c.set( Calendar.HOUR, selectedHour );
c.set( Calendar.MINUTE, selectedMinute );
// Have Calendar calculate the substraction of hours and minutes
c.add( Calendar.HOUR, SUB_HOUR );
c.add( Calendar.MINUTE, SUB_MINUTE );
// Get the hour and the minute calculated
hour = c.get( Calendar.HOUR );
minute = c.get( Calendar.MINUTE );
如果你没有看到任何格式,请原谅..
答案 0 :(得分:6)
Changue:
wakingtime.setText( new StringBuilder().append( pad( hour ))
.append( ":" ).append( pad( minute )));
由此:
StringBuilder sb = new StringBuilder();
if(hour>=12){
sb.append(hour-12).append( ":" ).append(minute).append(" PM");
}else{
sb.append(hour).append( ":" ).append(minute).append(" AM");
}
wakingtime.setText(sb);
答案 1 :(得分:0)
你可以使用
String s;
if(hour>=12){
s=String.formate((hour-12)+":"+minute+"PM");
}else{
s=String.formate(hour+":"+minute+"AM");
}
txtview.setText(s);
答案 2 :(得分:0)
scheduleTime.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Calendar mcurrentTime = Calendar.getInstance();
int hour = mcurrentTime.get(Calendar.HOUR_OF_DAY);
int minute = mcurrentTime.get(Calendar.MINUTE);
TimePickerDialog mTimePicker;
mTimePicker = new TimePickerDialog(activity, new TimePickerDialog.OnTimeSetListener() {
@Override
public void onTimeSet(TimePicker timePicker, int selectedHour, int selectedMinute) {
String choosedHour = "";
String choosedMinute = "";
String choosedTimeZone = "";
if(selectedHour > 12){
choosedTimeZone = "PM";
selectedHour = selectedHour - 12;
if(selectedHour < 10){
choosedHour = "0"+selectedHour;
}else{
choosedHour = ""+selectedHour;
}
}else{
choosedTimeZone = "AM";
if(selectedHour < 10){
choosedHour = "0"+selectedHour;
}else{
choosedHour = ""+selectedHour;
}
}
if(selectedMinute < 10){
choosedMinute = "0"+selectedMinute;
}else{
choosedMinute= ""+selectedMinute;
}
scheduleTime.setText(choosedHour + ":" + choosedMinute +" "+choosedTimeZone);
//scheduleTime.setText(selectedHour + ":" + selectedMinute);
//scheduleTime.setText( strHrsToShow+":"+datetime.get(Calendar.MINUTE)+" "+am_pm );
}
}, hour, minute+30, false);//Yes 24 hour time
mTimePicker.setTitle("Select Time");
mTimePicker.show();
}
});
我用这个逻辑来解决我的问题。