问题描述
|
使用日历类确定上午或下午时间。
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);
解决方法
这是正常的。因为
Calendar.MONTH
的索引从0开始。因此,为什么需要+1
才能获取正确的Month。
, 只需检查calendar.get(Calendar.AM_PM) == Calendar.AM
Calendar now = Calendar.getInstance();
if(now.get(Calendar.AM_PM) == Calendar.AM){
// AM
}else{
// PM
}
, 确定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\";
}
, 我试过了,但是没有用。我必须获取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
}