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
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.
GregorianCalendar
is notDate
, you can convert it toDate
, then use the code in your link:I would suggest to use
java.time
package to deal with date and time.