Using calendar to determine AM or PM dates
Using the calendar class to determine AM or PM times.
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_MO开发者_如何转开发NTH);
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){}
I want to set the time to AM or PM depending on the current time. also for some reason the Calendar.MONTH value doesn't give me the correct month. It's off by one so thats why I had to add 1. Just wondering if thats normal?
int months = 1 + c.get(Calendar.MONTH);
It is normal. Because the index of the Calendar.MONTH
starts from 0. So that why you need +1
to get the correct Month.
Simply check calendar.get(Calendar.AM_PM) == Calendar.AM
Calendar now = Calendar.getInstance();
if(now.get(Calendar.AM_PM) == Calendar.AM){
// AM
}else{
// PM
}
Determining AM vs. PM is a straightforward calculation based on hour. Here's the code:
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";
}
I tried this, but it doesn´t work. I have to obtain the AM_PM value and then make the comparison:
int AM_PM = c.get(Calendar.AM_PM);
if(AM_PM == Calendar.AM){
...
...
It was solution:
Calendar c = Calendar.getInstance();
int AM_PM = c.get(Calendar.AM_PM);
if(AM_PM == Calendar.AM){
//AM
}else{
//PM
}
精彩评论