在jquery中格式化所选日期

问题描述

我没有输入就显示datepicker。我想获取所选日期并将其格式化为dd-mm-yy,但是它不起作用。

enter image description here

$(function() {
    var selectedDate = $("#inline-calendar").datepicker({
        changeYear: true,dateFormat: 'dd-mm-yy',}).datepicker("setDate","Now").datepicker("getDate");

    console.log(selectedDate)
});
<div id="inline-calendar"></div>

以上代码输出Sat Sep 12 2020 00:00:00 GMT+0800 (Singapore Standard Time)

解决方法

您只需在.data引导中使用datepicker属性,即可使用getFormattedDate

获取日历上日期的值。

实时工作演示:

$(function() {
  $("#inline-calendar").datepicker({
    changeYear: true,dateFormat: 'dd-mm-yy',}).datepicker("setDate","now").datepicker("getDate");
    
  //get date value
  let getDate = $("#inline-calendar").data('datepicker').getFormattedDate('dd-mm-yy');

  console.log(getDate) //12-09-20
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.9.0/js/bootstrap-datepicker.min.js" integrity="sha512-T/tUfKSV1bihCnd+MxKD0Hm1uBBroVYBOYSk1knyvQ9VyZJpc/ALb4P0r6ubwVPSGB2GvjeoMAJJImBG12TiaQ==" crossorigin="anonymous"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.9.0/css/bootstrap-datepicker.min.css" integrity="sha512-mSYUmp1HYZDFaVKK//63EcZq4iFWFjxSL+Z3T/aCt4IO9Cejm03q3NKKYN6pFQzY0SBOr8h+eCIAZHPXcpZaNw==" crossorigin="anonymous" />

<div id="inline-calendar"></div>