oon arfiandwi
oon arfiandwi

Reputation: 555

Format date of bootstrap datepicker

I'm using bootstrap datepicker on form with ajax to update date limit on the datepicker.

I hit the ajax to get total days and setEndDate of datepicker to limit upper date (all later dates will be disabled).

$.ajax({
    url: url,
    type: 'POST',
    dataType: 'json',
    success: function (data) {
        if('total' in data && data['total'] > 1) {

            // datepicker successfully set the limit to next 'total' days
            $datepicker.datepicker('setEndDate', '+'+data['total']+'d');

            // how to set the field value with that end date?
            $datepicker.val($datepicker.datepicker('getEndDate'));
        }
    },
    error: function (e) {
        console.log(e);
    }
});

my question is how to format $datepicker.datepicker('getEndDate'), to yyyy-mm-dd? currently it returns Fri Jul 27 2018 08:00:00 GMT+0800 (Singapore Standard Time).

I have check the documentation [1], but no parameter to assign on formatting the getEndDate.

appreciated any help. thank you.

edit:

for anyone that having some problem with me, currently my solution is parsing the return of $datepicker.datepicker('getEndDate') manually.

I saw the output was equal with Date .toString(), so I pass the output as JavaScript Date constructor then format it manually.

var d = new Date($datepicker.datepicker('getEndDate'));
if(d instanceof Date && !isNaN(d)) {
    var day = '' + d.getDate(),
        month = '' + (d.getMonth() + 1),
        year = d.getFullYear();
    if (month.length < 2) month = '0' + month;
    if (day.length < 2) day = '0' + day;

    // console.log([year, month, day].join('-'));
    $datepicker.datepicker('update', [year, month, day].join('-'));
}

[1]http://bootstrap-datepicker.readthedocs.io/en/latest/methods.html

Upvotes: 0

Views: 1877

Answers (1)

Vignesh Raja
Vignesh Raja

Reputation: 8731

You can use $("#date").data("datepicker").getFormattedDate() but it gives the format of the selected date.

So you need to use the getEndDate() of the datepicker to get the end date and DPGlobal object to parse the date.

$("#date").datepicker({
    format:"dd/mm/yyyy",
    endDate:"26/07/2018"
});

function getDate()
{
   var date = $.fn.datepicker.DPGlobal.formatDate($("#date").data("datepicker").getEndDate(),"dd-mm-yyyy","en")
   console.log(date)
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.8.0/js/bootstrap-datepicker.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css"/>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.3.0/css/datepicker.css"/>

<input id="date">
<button onclick="getDate()">Get Date</button>

Upvotes: 2

Related Questions