Datepicker格式getDate

时间:2017-04-14 13:31:53

标签: javascript jquery datepicker

我需要将日期设为yyyy-MM-dd,但我总是采用不同的格式。如何获得我想要的datepicker值?

https://jsfiddle.net/041h6mss/

HTML:

<input id="thedate" type="text" />
<input type="button" id="button" value="submit" />
<span id="output"></span>

JS:

$(function(){

    $("#thedate").datepicker({
        dateFormat: "D, M d, yy",
    });
})
var output = document.getElementById("output");

document.getElementById("button").onclick = function() {
    output.innerHTML = $("#thedate").datepicker("getDate");
};

我的价值为Mon Apr 03 2017 00:00:00 GMT+0200 (CEST),但我希望它为2017-03-03

2 个答案:

答案 0 :(得分:2)

我已经更新了答案。请在此处查看:https://jsfiddle.net/041h6mss/1/

HTML:

<input id="thedate" type="text" />
<input id="altField" type="hidden" />
<input type="button" id="button" value="submit" />
<span id="output"></span>

使用Javascript:

$(function(){
    $("#thedate").datepicker({
        dateFormat: "D, M d, yy",
        altField: "#altField",
        altFormat: "yy-mm-dd"
    });
})
var output = document.getElementById("output");

document.getElementById("button").onclick = function() {
    output.innerHTML = $("#altField").val();
};

或者,你也可以试试这个(更好的解决方案):

document.getElementById("button").onclick = function() {
    output.innerHTML = $.datepicker.formatDate("yy-mm-dd", $("#thedate").datepicker("getDate"));
};

答案 1 :(得分:1)

您的日期格式不正确,需要将其更改为yy-mm-dd

$(function(){
    $("#thedate").datepicker({
        dateFormat: "yy-mm-dd"
    });
})
var output = document.getElementById("output");

document.getElementById("button").onclick = function() {
    output.innerHTML = $("#thedate").datepicker("getDate");
};