如何在javascript中更改datepicker值的日期格式

时间:2014-06-13 05:23:46

标签: javascript html datepicker date-formatting

我去了很多与问题有关的stackoverflow问题,但我仍然无法找到任何解决方案。我试图从我的javascript函数中获取datpicker的值,但无法更改其格式。默认情况下,它以mm / dd / yy格式显示,我希望采用yyyy-mm-dd格式。任何人都可以帮忙。

以下是我的HTML代码:

    <html xmlns:h="http://xmlns.jcp.org/jsf/html">
    <h:head>
    <script>
        function getdate()
        {
         alert("Entered function");
      var date = $('#fromdate').val();
          $.datepicker.formatDate( 'yy-mm-dd' ,date );
            alert(date); }
        </script>
     </h:head>
    <body>
      <input type="text" id="fromdate" class="form-control dpd1" name="from"placeholder="Select From Date"></input>
      <span class="input-group-addon">To</span>
      <input type="text" id="todate" class="form-control dpd2" name="to" placeholder="Select To Date" ></input>
      <input type="button" onclick="getdate()" value="Change Date"></input>

    </body>
    </html>

提前致谢。

5 个答案:

答案 0 :(得分:3)

    <script>

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

    });

    function getdate()
    {
     alert("Entered function");
     var date = $('#fromdate').val();
     alert(date);
     }
    </script>

答案 1 :(得分:3)

日期格式可以是以下任何字符的组合:

d – day of month (single digit where applicable)
dd – day of month (two digits)
m – month of year (single digit where applicable)
mm – month of year (two digits)
y – year (two digits)
yy – year (four digits)
D – short day name
DD – full day name
M – short month name
MM – long month name
'...' – any literal text string
@ - UNIX timestamp (milliseconds since 01/01/1970)

答案 2 :(得分:0)

function getdate()
{
    alert("Entered function");
    var date = $('#fromdate').val();
    date = $.datepicker.formatDate( 'yy-mm-dd', date );
    alert(date);
}

您需要将formatDate调用的结果分配给日期对象。然后你可以提醒它。

答案 3 :(得分:0)

HTML

<input type="text" id="fromdate" class="datepicker form-control dpd1" name="from" placeholder="Select From Date"></input> <span class="input-group-addon">To</span>

<input type="text" id="todate" class="datepicker form-control dpd2" name="to" placeholder="Select To Date"></input>
<input type="button" class="getdate" value="Change Date"></input>

的JavaScript

//Define fields with class name 'datepicker' as jQueryUI datepicker
$('.datepicker').datepicker({
    dateFormat: 'yy-mm-dd' //Setting dateformat for the datepicker
});

//Binding 'onclick' function for the button with class name 'getdate'
$('.getdate').on('click', function () {
    var date = $('#fromdate').val();
    alert(date);
});

JSFiddle

答案 4 :(得分:0)

它适用于我

<input type="text" id="fromdate" class="form-control dpd1"    name="from"placeholder="Select From Date"></input>

$('#fromdate').datepicker({
    format: 'yyyy/mm/dd'
});