Search code examples
javarestglassfishstring-formattingpayara

How to stop the String from being interpreted as DateTime in Payara?


Good day everyone! I have a get method in rest and the result is stored in something like this:

@XmlRootElement(name = "FooDTO")
public class Foo {
    @XmlElement(nillable = true)
    private String approvedDate;
    private static final DateFormat DEFAULT_DATE_FORMAT = new SimpleDateFormat(
        "dd.MM.yyyy");


    public Date getApprovedDate() {
        try {
            return StringUtils.isBlank(approvedDate) ? null
                    : DEFAULT_DATE_FORMAT.parse(approvedDate);
        } catch (ParseException e) {
            e.printStackTrace();
            return null;
        }
    }

    public void setApprovedDate(Date approvedDate) {
        this.approvedDate = approvedDate == null ? "" : DEFAULT_DATE_FORMAT
                .format(approvedDate);
    }
}

It works in Glassfish server and I get approvedDate as a String in dd.MM.yyyy format. However, in Payara, the String is getting formatted to yyyy-MM-ddTHH:mm:ssZ[Timezone]. How do I adjust this so that the String doesn't get "interpreted" as DateTime? Thanks!


Solution

  • As I see you have a field approvedDate that is private so the the process marshal/unmarshal accesses this field through the get/set, in this case it's returning as Date type on the getApprovedDate method.

    Try:

    @XmlRootElement(name = "FooDTO")
    public class Foo {
    
        @XmlElement(nillable = true)
        private String approvedDate;
        private static final DateFormat DEFAULT_DATE_FORMAT = new SimpleDateFormat("dd.MM.yyyy");
    
    
        public String getApprovedDate() {
            return approvedDate;
        }
    
        public void setApprovedDate(Date approvedDate) {
            this.approvedDate = approvedDate == null ? "" : DEFAULT_DATE_FORMAT
                    .format(approvedDate);
        }
    }