Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

overriding tostring method in Gregorian Calendar

Tags:

java

using inner class, i'm overriding toString method of Gregorian Calendar:

 GregorianCalendar date = new GregorianCalendar(2010, 5, 12)
      {
          public String toString()
          {
              return String.format("%s/%s/%s", YEAR, MONTH, DAY_OF_MONTH);
          }
      };

when i print date it should be something like this:

2010/5/12

but the output is:

1/2/5

like image 948
Branky Avatar asked Dec 02 '22 23:12

Branky


1 Answers

YEAR, MONTH and DAY_OF_MONTH are just field numbers to use in get and set methods. This is how it works

        public String toString() {
            return String.format("%d/%02d/%02d", get(YEAR), get(MONTH) + 1, get(DAY_OF_MONTH));
        }

note that month in Calendar starts with 0, this is why we need get(MONTH) + 1

like image 62
Evgeniy Dorofeev Avatar answered Dec 05 '22 13:12

Evgeniy Dorofeev