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);
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";
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With