Question

I had a look at the java api about GregorianCalendar and did not see any way of setting the am/pm in its constructor. Can you set AM/PM in a GregorianCalendar date or is it something you can only get using a get method on the calendar. Does it handle all of this automatically. I am looking to take the am/pm and output it in my toString for a class which has a date object. I was going to use the get method on the calendar to get this. I understand the the am/pm is an int that is 0 or 1.

I was also wondering if all hours are 24 hours in gregorian and it automatically determines the am and pm?

Was it helpful?

Solution

Calendar.get(Calendar.HOUR);

Gives the hour (0-12) for AM/PM format.

Calendar.get(Calendar.HOUR_OF_DAY);

Gives the hour ranging from 0-24.

It does the conversion on its own. You don't need to tell it.

cal.set( Calendar.AM_PM, Calendar.AM )

Will/Could change the point time this calendar object represents. (If it's 1:00PM you will have 1:00AM afterwards). This is true for GregorianCalendar (see comment to question by Peter Cetinski).

Btw/Hint imo you should use a DateFormat to ouput your preferred format.

OTHER TIPS

Calendar cal = new GreogorianCalendar();   
cal.set( Calendar.AM_PM, Calendar.AM );

Simply I did this :

Calendar calendar = new GregorianCalendar();
    int seconds = calendar.get(Calendar.SECOND);
    int minutes = calendar.get(Calendar.MINUTE);
    int hour = calendar.get(Calendar.HOUR);
    int am_pm = calendar.get(Calendar.AM_PM);
    String ampm = "ampm";
    if (am_pm == 0) {
        ampm = "AM";
    } else {
        ampm = "PM";
    }
    jLabel1.setText(hour + ":" + minutes + ":" + seconds + " " + ampm);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top