public void setCurrenttime () {
c = Calendar.getInstance();
hour = c.get(Calendar.HOUR_OF_DAY);
min = c.get(Calendar.MINUTE);
String am_pm;
if (hour > 12) {
am_pm = "PM";
} else {
am_pm = "AM";
}
tvDisplayHour=(TextView)findViewById(R.id.hourtext);
tvDisplayHour.setText(hour+":"+ min + " "+ am_pm );
}
我的问题是它不会在我的模拟器中设置当前时间。
该代码有什么问题?请帮助我是android的新手。
谢谢
public void setCurrenttime () {
c = Calendar.getInstance();
hour = c.get(Calendar.HOUR_OF_DAY);
min = c.get(Calendar.MINUTE);
String am_pm;
if (hour > 12) {
am_pm = "PM";
} else {
am_pm = "AM";
}
tvDisplayHour=(TextView)findViewById(R.id.hourtext);
tvDisplayHour.setText(hour+":"+ min + " "+ am_pm );
}
在此代码中我如何转换为12小时格式?
答案 0 :(得分:2)
您正在使用的代码是从系统中获取时间而不是为系统设置时间。如果要将时间设置为System,则需要使用AlarmManager类。检查以下代码,
Calendar c = Calendar.getInstance();
c.set(2014, 8, 15, 12, 34, 56);
AlarmManager am = (AlarmManager) this.getSystemService(Context.ALARM_SERVICE);
am.setTime(c.getTimeInMillis());
您还需要在AndroidManifest.xml
文件中定义以下权限
<permission android:name="android.permission.SET_TIME"
android:protectionLevel="signature|system"
android:label="@string/permlab_setTime"
android:description="@string/permdesc_setTime" />
答案 1 :(得分:0)
试试这个: 您将获得当前时间: -
根据您的要求修改它: -
public void current_time() {
Calendar cal = Calendar.getInstance();
int hour = cal.get(Calendar.HOUR_OF_DAY);
int minute = cal.get(Calendar.MINUTE);
int am_pm = cal.get(Calendar.AM_PM);
TimePickerDialog mTimePicker;
mTimePicker = new TimePickerDialog(InformationActivity.this,
new TimePickerDialog.OnTimeSetListener() {
@Override
public void onTimeSet(TimePicker timePicker,
int selectedHour, int selectedMinute) {
String minutes = "";
int startTimeHour = selectedHour;
int startTimeMinute = selectedMinute;
if (selectedMinute < 10) {
minutes = "0" + selectedMinute;
} else {
minutes = String.valueOf(selectedMinute);
}
if (selectedHour > 12) {
selectedHour -= 12;
String timeSet_in = "PM";
edt_time_in.setText(selectedHour + ":" + minutes
+ " " + timeSet_in.toString());
selectedHour += 12;
} else if (selectedHour == 0) {
selectedHour += 12;
timeSet_in = "AM";
edt_time_in.setText(selectedHour + ":" + minutes
+ " " + timeSet_in.toString());
selectedHour -= 12;
} else if (selectedHour == 12) {
timeSet_in = "PM";
edt_time_in.setText(selectedHour + ":" + minutes
+ " " + timeSet_in.toString());
} else {
timeSet_in = "AM";
edt_time_in.setText(selectedHour + ":" + minutes
+ " " + timeSet_in.toString());
}
arriveLoadHour = selectedHour;
arriveLoadMinute = selectedMinute;
}
}, hour, minute, true);// Yes 24 hour time
mTimePicker.setTitle("Select Time");
mTimePicker.show();
}