Skip to content
Advertisement

Converting a Java Timestamp into a String?

I have the following field in my Java Entity:

@JsonProperty
@Temporal(TemporalType.TIMESTAMP)
@Column(name = "start_date")
private Calendar startDate;

It is currently a timestamp when we send it to the front end via json.

How can I convert this into a string to send to front end?

Advertisement

Answer

You can use @JsonSerialize annotation.

@JsonProperty
@Temporal(TemporalType.TIMESTAMP)
@Column(name = "start_date")
@JsonSerialize(using = CalenderSerializer.class)
private Calendar startDate;

Serializer:

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Locale;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.ser.std.StdSerializer;

public class CalenderSerializer extends StdSerializer<Calendar> {

    private static final long serialVersionUID = 72941023713498596L;
    private static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.ENGLISH);

    public CalenderSerializer() {
        this(null);
    }

    public CalenderSerializer(Class<Calendar> t) {
        super(t);
    }

    @Override
    public void serialize(Calendar value, JsonGenerator gen, SerializerProvider provider) throws IOException {
        gen.writeString(sdf.format(value.getTime()));
    }
}
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement