skip to Main Content

I am implementing toString methods for my entities. There are a lot of fields of type ZonedDateTime. Unfortunately, it’s converted to extremely long text representation:

java.util.GregorianCalendar[
  time=1545826815293,
  areFieldsSet=true,
  areAllFieldsSet=true,
  lenient=true,
  zone=sun.util.calendar.ZoneInfo
  [
    id=
    "UTC",
    offset=0,
    dstSavings=0,
    useDaylight=false,
    transitions=0,
    lastRule=null
  ],
  firstDayOfWeek=1,
  minimalDaysInFirstWeek=1,
  ERA=1,
  YEAR=2018,
  MONTH=11,
  WEEK_OF_YEAR=52,
  WEEK_OF_MONTH=5,
  DAY_OF_MONTH=26,
  DAY_OF_YEAR=360,
  DAY_OF_WEEK=4,
  DAY_OF_WEEK_IN_MONTH=4,
  AM_PM=1,
  HOUR=0,
  HOUR_OF_DAY=12,
  MINUTE=20,
  SECOND=15,
  MILLISECOND=293,
  ZONE_OFFSET=0,
  DST_OFFSET=0
]

How can I format it using SimpleDateFormat?
I tried the example given here:
https://howtodoinjava.com/apache-commons/how-to-override-tostring-effectively-with-tostringbuilder/

public class CustomToStringStyle extends ToStringStyle
{
    private static final long serialVersionUID = 1L;
    protected void appendDetail(StringBuffer buffer, String fieldName, Object value)
    {
         if (value instanceof Date)
         {
             value = new SimpleDateFormat("yyyy-MM-dd").format(value);
         }
         buffer.append(value);
     }
}

But in this case, I don’t use JSON style of formatting. I can’t extend JsonToStringStyle because it’s private.

2

Answers


  1. ZonedDateTime is part of the new Java 8 API while SimpleDateFormat is the old buggy Date formatter. You need to use the new DateFormatter for Java 8 date/time classes.

    The JSON you posted however is neither a ZonedDateTime, nor a Date, it is a GregorianCalendar, so not sure whether your problem is really to do with ZonedDateTime as you are saying.

    Login or Signup to reply.
  2. GregorianCalendar is not Date, you can convert it to Date, then use the code in your link:

    if (value instanceof calendar)
    {
        Date date = new Date(value.getTimeInMillis());
        value = new SimpleDateFormat("yyyy-MM-dd").format(date);
    }
    

    I would suggest to use java.time package to deal with date and time.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search