Overriding the tostring method in a Gregorian calendar

using the inner class, I override the toString method in the 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 the date it should be something like this:

2010/5/12

but conclusion:

1/2/5

+4
source share
3 answers

YEAR , MONTH and DAY_OF_MONTH are simply field numbers to use in the get and set methods. Here's how it works.

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

Note that the month on the calendar starts at 0, so we need to get(MONTH) + 1

+7
source

This should give you what you expect:

 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); } }; 
+7
source

You are almost there .. but YEAR, MONTH refer to transfers, and what you print is the serial number of these transfers. You want real value using these enumerations with 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.

+3
source

Source: https://habr.com/ru/post/1482686/


All Articles