使用日历类确定上午或下午时间。
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){}
我想根据当前时间将时间设置为AM或PM。 由于某种原因,Calendar.MONTH值也没有给我正确的月份。这是一个关闭因此我必须添加1.只是想知道这是否正常?
int months = 1 + c.get(Calendar.MONTH);
答案 0 :(得分:8)
这很正常。因为Calendar.MONTH
的索引从0开始。所以你需要+1
来获得正确的月份。
答案 1 :(得分:5)
确定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";
}
答案 2 :(得分:5)
只需查看calendar.get(Calendar.AM_PM) == Calendar.AM
Calendar now = Calendar.getInstance();
if(now.get(Calendar.AM_PM) == Calendar.AM){
// AM
}else{
// PM
}
答案 3 :(得分:0)
我试过了this,但它不起作用。我必须获取AM_PM值然后进行比较:
int AM_PM = c.get(Calendar.AM_PM);
if(AM_PM == Calendar.AM){
...
...
这是解决方案:
Calendar c = Calendar.getInstance();
int AM_PM = c.get(Calendar.AM_PM);
if(AM_PM == Calendar.AM){
//AM
}else{
//PM
}