我使用的UI DatePicker从jQuery UI作为独立的选择器。我有这样的代码:

<div id="datepicker"></div>

和下面的JS:

$('#datepicker').datepicker();

当我尝试用下面的代码返回值时:

var date = $('#datepicker').datepicker('getDate');

我得到的答复是:

Tue Aug 25 2009 00:00:00 GMT+0100 (BST)

这是完全错误的格式。有没有办法让它以DD-MM-YYYY格式返回?


当前回答

这里有一个特定的代码:

var date = $('#datepicker').datepicker({ dateFormat: 'dd-mm-yy' }).val();

更多信息可在这里:

http://api.jqueryui.com/datepicker/#option-dateFormat http://api.jqueryui.com/datepicker/#utility-formatDate

其他回答

<script type="text/javascript">
  $(function() {
    $( "#date" ).datepicker( {minDate: '0', dateFormat: 'yy-dd-mm' } );
  });
</script>

我的选择如下:

$(document).ready(function () { var userLang = navigator.language || navigator.userLanguage; var options = $.extend({}, $.datepicker.regional["ja"], { dateFormat: "yy/mm/dd", changeMonth: true, changeYear: true, highlightWeek: true } ); $("#japaneseCalendar").datepicker(options); }); #ui-datepicker-div { font-size: 14px; } <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/themes/smoothness/jquery-ui.min.css"> <script src="https://code.jquery.com/jquery-3.2.1.min.js"></script> <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.11.1/i18n/jquery-ui-i18n.min.js"></script> </head> <body> <h3>Japanese JQuery UI Datepicker</h3> <input type="text" id="japaneseCalendar"/> </body> </html>

这里是一个开箱即用的未来证明日期片段。Firefox默认为jquery ui datepicker。否则使用HTML5 datepicker。如果FF支持HTML5 type="date",脚本将是多余的。不要忘记head标签中需要三个依赖项。

<script>
  src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js">
</script>
<link rel="stylesheet"href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">  
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>

<!--Form element uses HTML 5 type="date"-->
<div class="form-group row">
    <label for="date" class="col-sm-2 col-form-label"Date</label>
    <div class="col-sm-10">          
       <input type="date" class="form-control" name="date" id="date" placeholder="date">
    </div>
</div>

<!--if the user is using FireFox it          
autoconverts type='date' into type='text'. If the type is text the 
script below will assign the jquery ui datepicker with options-->
<script>
$(function() 
{
  var elem = document.createElement('input');
  elem.setAttribute('type', 'date');

  if ( elem.type === 'text' ) 
  {
    $('#date').datepicker();
    $( "#date" ).datepicker( "option", "dateFormat", 'yy-mm-dd' );     
  }
});

如果你需要年月日格式的日期,你可以使用这个:-

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

您可以找到所有受支持的格式 https://jqueryui.com/datepicker/#date-formats

我在2015年12月6日需要,我这样做了:-

$("#datepicker").datepicker({ dateFormat: "d M,y" });

这对我来说很管用:

$.fn.datepicker.defaults.format = 'yy-mm-dd'