Paul Phoenix Paul Phoenix - 1 month ago 19
jQuery Question

jquery date picker set date format as 'MM-DD-YYYY' from a string containing datetime

I am trying to set the jquery datepicker date format but it is not working, I have read few posts and answer already but none of them worked for me. Below is the code I am using please check and tell me where I am doing wrong. I am getting the datetime from Database as

2012-03-06 00:00:00 UTC


<script>
$(document).ready(function() {
$(".datepicker").datepicker({
dateFormat:'MM-DD-YYYY'
}).val();
});
</script>


Also I tried

<script>
$(document).ready(function() {
var dateTypeVar = $('.datepicker').datepicker('getDate');
$.datepicker.formatDate('dd-mm-yy', dateTypeVar);
});
</script>

Answer

This 2012-03-06 00:00:00 UTC is not a valid JavaScript date, so the datepicker can't accept the value assigned.

Date object: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date

setDate method: http://api.jqueryui.com/datepicker/#method-setDate

Get the date in a compliant format, and then set the datepicker in this way.

Code:

$(document).ready(function () {
    var dbDate = "2012-03-06";
    var date2 = new Date(dbDate);

    $(".datepicker").datepicker({
        dateFormat: 'mm-dd-yy'
    }).datepicker('setDate', date2)

});

Demo: http://jsfiddle.net/IrvinDominin/7ck7D/