Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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_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);
like image 346
cj1098 Avatar asked Jun 04 '11 04:06

cj1098


3 Answers

It is normal. Because the index of the Calendar.MONTH starts from 0. So that why you need +1 to get the correct Month.

like image 194
Andrei Sfat Avatar answered Sep 29 '22 21:09

Andrei Sfat


Simply check calendar.get(Calendar.AM_PM) == Calendar.AM

Calendar now = Calendar.getInstance();
if(now.get(Calendar.AM_PM) == Calendar.AM){
   // AM
}else{
   // PM
}
like image 27
Linh Avatar answered Sep 29 '22 20:09

Linh


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";
}
like image 41
PeteH Avatar answered Sep 29 '22 19:09

PeteH