Max Mumford
Max Mumford

Reputation: 2642

Custom DateTime format in Spring Data Projection

I have a spring data projection that inlines some relational fields. When the projection is applied, datetime fields are no longer outputted as iso8601 (like they are without the projection), but are instead outputted in another format.

How do I make my projection format a datetime as ISO8601? Here's my projection currently:

package io.cocept.model.projection;

import io.cocept.model.Meeting;
import io.cocept.model.User;
import org.springframework.data.rest.core.config.Projection;
import org.springframework.format.annotation.DateTimeFormat;

@Projection(name = "inlineUsers", types = { Meeting.class })
public interface MeetingInlineUsersProjection {

    String getAddress();
    String getDateTime();    
    String getMessage();

    User getOwner();
    User getInvitee();

}

and my Meeting class:

package io.cocept.model;

import javax.persistence.*;
import javax.validation.constraints.NotNull;
import java.util.Date;

@Entity
public class Meeting extends BaseEntity {

    private User owner;
    private User invitee;
    private String address;
    private Date dateTime;
    private String message;

    public Meeting() {

    }


    @ManyToOne
    @NotNull
    @JoinColumn(name = "owner_id")
    public User getOwner() {
        return owner;
    }
    public void setOwner(User owner) {
        this.owner = owner;
    }

    @ManyToOne
    @NotNull
    @JoinColumn(name = "invitee_id")
    public User getInvitee(){
        return invitee;
    }
    public void setInvitee(User invitee){
        this.invitee = invitee;
    }

    @NotNull
    public String getAddress() {
        return address;
    }
    public void setAddress(String address) {
        this.address = address;
    }

    @NotNull
    public Date getDateTime() {
        return dateTime;
    }
    public void setDateTime(Date dateTime) {
        this.dateTime = dateTime;
    }

    public String getMessage(){ return message; }
    public void setMessage(String message){ this.message = message; }

}

I've tried adding the decorator @DateTimeFormat(pattern = "YYYY") to the getDateTime() property but it doesn't change the outputted date format.

Any ideas?

Thanks Max

Upvotes: 3

Views: 5086

Answers (2)

Max Mumford
Max Mumford

Reputation: 2642

As pointed out by Jens Schauder in their comment, I had accidentally set the type for getDateTime() in the projection as String, as opposed to Date. This presumably made an implicit toString conversion in a different format to the spring default (iso8601).

When I changed the projection from:

String getDateTime()

to:

Date getDateTime()

it formatted the date as ISO8601 like the rest of the app.

Upvotes: 2

Dean Clark
Dean Clark

Reputation: 3878

Try @DateTimeFormat(pattern = "yyyy") instead of YYYY.

Upvotes: 0

Related Questions