Home > database >  Define the toString() method for a Date field
Define the toString() method for a Date field

Time:04-05

I am using java and SpringBoot and I wonder if there is an easy way to define a toString() method for a field of type Date.

public class MyClass {
   private Date date
}

So that when calling

myClassInstance.getDate().toString()

I'll get it in YYYY-MM-DDTHH:mm:ssZ?

I need it since I want to use BeanUtils.copyProperties(dest, orig). In orig the field is a Date and in dest I want it to be a string. right now I am able to convert it but it is converted to this kind of date: Wed Apr 06 00:00:00 UTC 2022 while I want it to be 'YYYY-MM-DDTHH:mm:ssZ'

CodePudding user response:

You can't redefine the toString() method for an existing class in Java. You could add a method to your class to return the formatted date:

public static class MyClass {
    private final Date date = new Date();

    public String dateAsString() {
        return new SimpleDateFormat("yyyy-MM-dd't'hh-mm-ssz").format(date);
    }
}

I wasn't sure what the "t" meant in the string, so I've put it as a literal.

CodePudding user response:

Ideally you would use the simple Date Formatter or the DateTimeFormatter from Java 8

Before Java 8

SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
String dateString = format.format( new Date()   );

Common patterns are

y   = year   (yy or yyyy)
M   = month  (MM)
d   = day in month (dd)
h   = hour (0-12)  (hh)
H   = hour (0-23)  (HH)
m   = minute in hour (mm)
s   = seconds (ss)
S   = milliseconds (SSS)
z   = time zone  text
Z   = time zone, time offset

After Java 8 can use the superior DateTimeFormatter which has a lot of pattern options (see link)

DateTimeFormatter formatter = DateTimeFormatter.BASIC_ISO_DATE;
String formattedDate = formatter.format(LocalDate.now());

patterns for this are described here:

Java 8 Documentation DateTimeFormatter Patterns

  • Related