Regardt Ogies Myburgh Regardt Ogies Myburgh - 11 days ago 4
jQuery Question

Javascript Calendar How to format dates exluding the zero

I have a javascript calendar that loads available dates from database. The calendar works and loads all dates that are open. The dates in my json string are dates that is booked.

the calendar loads these dates but dates that start with "0"1 or "0"2 etc dont show because the script sees it as 1 or 2 without the "0".

Please have a look at my code below.



<script type="text/javascript">
var unavailableDates = ["2016-11-24","2016-11-25","2016-11-26","2016-12-01"];

function unavailable(date) {

dmy = date.getFullYear() + "-" + (date.getMonth() + 1) + "-" + date.getDate() ;
if ($.inArray(dmy, unavailableDates) == -1) {
return [true, ""];
} else {
return [false, "", "Unavailable"];
}
}

$(function() {
$(".startdate").datepicker({
defaultDate: new Date(),
dateFormat: 'yy-mm-dd',

beforeShowDay: unavailable,
minDate:'0d'
});

});
</script>




Answer

You need left-padding:

var y = date.getFullYear();
var m = date.getMonth() + 1;
var d = date.getDate();
dmy = y + "-" + 
      (m<=9 ? "0" : "" ) + m + "-" + 
      (d<=9 ? "0" : "" ) + d;
Comments