【发布时间】:2011-09-08 05:59:06
【问题描述】:
使用日历类来确定上午或下午时间。
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){}
我想根据当前时间将时间设置为上午或下午。 也出于某种原因 Calendar.MONTH 值没有给我正确的月份。差了一个,所以我必须加 1。只是想知道这是否正常?
int months = 1 + c.get(Calendar.MONTH);
【问题讨论】:
-
附带说明,没有理由使用 if/else 子句,只需说 String AM_PM = ""; if (AM_orPM == 1){ AM_PM = "PM"; } 其他 { AM_PM = "上午"; }