Sami
Sami

Reputation: 2331

How to convert Datepicker-date to Java.util.Date?

ERROR Message

org.codehaus.jackson.map.JsonMappingException: Can not construct instance of java.util.Date from String value '02/23/2013': not a valid representation (error: Can not parse date "02/23/2013": not compatible with any of standard forms ("yyyy-MM-dd'T'HH:mm:ss.SSSZ", "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", "EEE, dd MMM yyyy HH:mm:ss zzz", "yyyy-MM-dd"))

Java object - entity

@Column(name = "event_date")
@Temporal(TemporalType.TIMESTAMP)
private Date eventDate;

Java Script

$(function() {
            $("#datepicker").datepicker();
        });

function formToJSON() {
            return JSON.stringify({
                   "eventDate": $('#datepicker').val()
            });
}

HTML

<input type="text" id="datepicker" name="date" placeholder="Date" />

Upvotes: 1

Views: 9718

Answers (3)

mgibsonbr
mgibsonbr

Reputation: 22007

There are probably better solutions out there, but since this is a problem I often run into and usually can't find a readily available tool, I ended up writing my own functions for that:

function dateFormat(date) {
    function two(v) { return v < 10 ? "0" + v : "" + v; }
    function four(v) { return v < 10 ? "000" + v : v < 100 ? "00" + v : v < 1000 ? "0" + v : "" + v; }
    var y = four(date.getFullYear());
    var m = two(date.getMonth()+1);
    var d = two(date.getDate());
    return y + "-" + m + "-" + d;
};

function datetimeFormat(date) {
    function two(v) { return v < 10 ? "0" + v : "" + v; }
    function three(v) { return v < 10 ? "00" + v : v < 100 ? "0" + v : "" + v; }
    function four(v) { return v < 10 ? "000" + v : v < 100 ? "00" + v : v < 1000 ? "0" + v : "" + v; }
    var y = four(date.getUTCFullYear());
    var m = two(date.getUTCMonth()+1);
    var d = two(date.getUTCDate());
    var h = two(date.getUTCHours());
    var mm = two(date.getUTCMinutes());
    var s = two(date.getUTCSeconds());
    var ms = three(date.getUTCMilliseconds());
    return y + "-" + m + "-" + d + "T" + h + ":" + mm + ":" + s + "." + ms;
};

The first one is what you need in your particular case, since you're only dealing with dates (and not time).

        return JSON.stringify({
               "eventDate": dateFormat($('#datepicker').datepicker('getDate'))
        });

Upvotes: 1

charlietfl
charlietfl

Reputation: 171669

datepicker includes a date formatting utility $.datepicker.formatDate

API reference: http://docs.jquery.com/UI/Datepicker/$.datepicker.formatDate

Try this:

function formToJSON() {
            var d= $('#datepicker').datepicker('getDate')
            return JSON.stringify({
                   "eventDate": $.datepicker.formatDate('yy-mm-dd', d)
            });
}

Upvotes: 2

Filip Vondr&#225;šek
Filip Vondr&#225;šek

Reputation: 1208

You could do:

$(function() {
   $("#datepicker").datepicker({
      dateFormat: "yy-mm-dd"
   });
});

Upvotes: 5

Related Questions