Branky
Branky

Reputation: 391

overriding tostring method in Gregorian Calendar

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

Upvotes: 4

Views: 4115

Answers (3)

Evgeniy Dorofeev
Evgeniy Dorofeev

Reputation: 136002

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

Upvotes: 7

greedybuddha
greedybuddha

Reputation: 7507

You are nearly there.. but the YEAR, MONTH are referring to enums, and what you are printing is the ordinal of those enums. What you want is to get the real value using those enums with the GregorianCalendar.get(Calendar.Value).

Example

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

that will fix your problems.

Upvotes: 3

Chris
Chris

Reputation: 5654

This should give you what you are expecting:

final SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
        GregorianCalendar date = new GregorianCalendar(2010, 5, 12)
        {
            public String toString()
            {
                Date thisDate = this.getTime();
                return sdf.format(thisDate);
            }
        };

Upvotes: 7

Related Questions