cj1*_*098 10 android calendar class
使用日历类确定AM或PM时间.
Calendar c = Calendar.getInstance();
int seconds = c.get(Calendar.SECOND);
int minutes = c.get(Calendar.MINUTE);
int hours = c.get(Calendar.HOUR);
int years = c.get(Calendar.YEAR);
int months = 1 + c.get(Calendar.MONTH);
int days = c.get(Calendar.DAY_OF_MONTH);
int AM_orPM = c.get(Calendar.AM_PM);
try{
if (hours < 12)
{
String PM = "";
if (AM_orPM == 1)
{
PM = "PM";
}
timestamp.setText("Refreshed on " + months + "-"
+ days + "-" + years + " " + hours + ":" + minutes + ":" + seconds + " " + PM);
timestamp.setTextSize(17f);
timestamp.setTextColor(Color.GREEN);
}
else if (hours > 12)
{
String AM = "";
if (AM_orPM == 0)
{
AM = "AM";
}
hours = hours - 12;
timestamp.setText("Refreshed on " + years + "-"
+ months + "-" + days + " " + hours + ":" + minutes + ":" + seconds + AM);
timestamp.setTextSize(17f);
timestamp.setTextColor(Color.GREEN);
}
}
catch (Exception e){}
Run Code Online (Sandbox Code Playgroud)
我想根据当前时间将时间设置为AM或PM.由于某种原因,Calendar.MONTH值也没有给我正确的月份.这是一个关闭因此我必须添加1.只是想知道这是否正常?
int months = 1 + c.get(Calendar.MONTH);
Run Code Online (Sandbox Code Playgroud)
这是正常的.因为索引Calendar.MONTH从0开始.所以你需要+1得到正确的月份.
只需检查 calendar.get(Calendar.AM_PM) == Calendar.AM
Calendar now = Calendar.getInstance();
if(now.get(Calendar.AM_PM) == Calendar.AM){
// AM
}else{
// PM
}
Run Code Online (Sandbox Code Playgroud)
确定AM与PM是基于小时的简单计算.这是代码:
String timeString="";
int hour = Calendar.getInstance().get(Calendar.HOUR_OF_DAY);
if (hour == 0) {
timeString = "12AM (Midnight)";
} else if (hour < 12) {
timeString = hour +"AM";
} else if (hour == 12) {
timeString = "12PM (Noon)";
} else {
timeString = hour-12 +"PM";
}
Run Code Online (Sandbox Code Playgroud)