Emerald
Emerald

Reputation: 409

Formatting selected date in jquery

I am displaying datepicker without an input. I want to get the selected date and format it to dd-mm-yy but it's not working.

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>

The output of the above code is Sat Sep 12 2020 00:00:00 GMT+0800 (Singapore Standard Time)

Upvotes: 1

Views: 45

Answers (1)

Always Helping
Always Helping

Reputation: 14570

You can simply use .data attributes in bootstrap datepicker to get the value of the date on the calendar using getFormattedDate

Live Working Demo:

$(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>

Upvotes: 1

Related Questions