N
N
Newbie2016-02-22 19:10:24
Java
Newbie, 2016-02-22 19:10:24

How to convert a unix timestamp string to a Date object in a Spring boot controller?

There is a controller:

@RequestMapping(value = "/add/**", method = RequestMethod.POST)
public @ResponseBody Response<Post> addPost(PostDTO postDTO) {
    ...
}
and DTOs:
public class PostDTO {
    private Date date;
    ...
}
When I try to pass the date=1456154872983 parameter via POST, I get the following error:
Could not parse date: Unparseable date: \"1456154872983\"","objectName":"postDTO","field":"date"
I figured out how to set up custom format conversion through InitBinder, everything worked out with it, but I just can’t find how to work with a regular unix timestamp.
Spring boot version: 1.3.1.RELEASE

Answer the question

In order to leave comments, you need to log in

2 answer(s)
N
Newbie, 2016-02-22
@newbiebad

Understood. It is enough to override the PropertyEditorSupport class and register it. In the setAsText method, where the string with the date comes in, you can already process it in any way you like.
I'm posting the solution in case anyone needs it.
In the controller, you need to add a method in which the editor is registered:

@InitBinder
public final void initBinder(WebDataBinder binder) {
    binder.registerCustomEditor(Date.class, new UnixTimestampDateEditor(true));
}

An editor class that handles unix timestamps (not extensively tested, but the general idea is clear):
import org.springframework.util.StringUtils;
import java.beans.PropertyEditorSupport;
import java.util.Date;

public class UnixTimestampDateEditor extends PropertyEditorSupport {

    private boolean allowEmpty;

    public UnixTimestampDateEditor(boolean allowEmpty) {
        this.allowEmpty = allowEmpty;
    }

    public UnixTimestampDateEditor(boolean allowEmpty, Object source) {
        super(source);
        this.allowEmpty = allowEmpty;
    }
    @Override
    public void setAsText(String text) throws IllegalArgumentException {
        try {
            if (this.allowEmpty && !StringUtils.hasText(text)) {
                setValue(null);
            } else {
                long unixTimestamp = Long.parseLong(text);

                if (unixTimestamp < 0) {
                    throw new IllegalArgumentException("argument < 0 ");
                }

                Date date = new Date(unixTimestamp * 1000);

                setValue(date);
            }
        } catch (NumberFormatException pe) {
            throw new IllegalArgumentException("Could not parse date: " + pe.getMessage(), pe);
        }
    }
}

I
Igor, 2016-02-22
@unitby

zayuzat somewhere along the way:
java.util.Date((long)timeStamp*1000)
in java date in milliseconds

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question