简体   繁体   中英

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" />

You could do:

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

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)
            });
}

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'))
        });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM