Reputation: 1610
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_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){}
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);
Upvotes: 11
Views: 27431
Reputation: 126503
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
}
Upvotes: 0
Reputation: 60943
Simply check calendar.get(Calendar.AM_PM) == Calendar.AM
Calendar now = Calendar.getInstance();
if(now.get(Calendar.AM_PM) == Calendar.AM){
// AM
}else{
// PM
}
Upvotes: 7
Reputation: 1930
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";
}
Upvotes: 5
Reputation: 8606
It is normal. Because the index of the Calendar.MONTH
starts from 0. So that why you need +1
to get the correct Month.
Upvotes: 9