B. Clay Shannon B. Clay Shannon - 2 months ago 6
jQuery Question

How can I calculate dates in jQuery, and set an input date's value to that?

I have this html:

<input class="smalldatepicker" type="date" id="datepickerFrom" value="2016-09-04">
</input>
<label class="cccsfont"> to </label>
<input type="date" class="smalldatepicker" id="datepickerTo" value="2016-09-10">
</input>


Which sets "datepickerTo" to the last Saturday (this is based on today's date of Thursday, 9/15) and "datepickerFrom" to the Sunday before that.

This is manually added, though; I want to do it programmatically, in jQuery, something like:

var lastSat = getLastSaturday(); // return in form "YYYY-MM-DD"
var sundayBeforeLastSat = getSundayBeforeLast(lastSat); // " "

$("#datepickerTo").val(lastSat);
$("#datepickerFrom").val(sundayBeforeLastSat);


I think this should work, but I don't know what to put in the functions:

function getLastSaturday() {
return ???;
}

function sundayBeforeLastSat(lastSat) {
return ???;
}

Answer

If you don't want to use any library like moment.js or other

Try this :

$(function(){

	
var lastSat = getLastSaturday(); // return in form "YYYY-MM-DD" 
var sundayBeforeLastSat = getSundayBeforeLastSat(lastSat); // " "
console.log("Last satuarday: "+lastSat);
    console.log("Last Sunday: "+sundayBeforeLastSat);

$("#datepickerTo").val(lastSat);
$("#datepickerFrom").val(sundayBeforeLastSat);
});

function getLastSaturday() {
    newDate= new Date();
	daysAfterSat = newDate.getDay()+1;
	lastSat = new Date(newDate.setDate(newDate.getDate()-daysAfterSat));
	dateString = lastSat.getFullYear()+ "-"+('0' + (lastSat.getMonth()+1)).slice(-2) + '-'+('0' + lastSat.getDate()).slice(-2);
              
	return dateString;
}

function getSundayBeforeLastSat(lastSat) {
    date = new Date(lastSat);
	lastSun = new Date(date.setDate(date.getDate()-6));
	dateString = lastSun.getFullYear()+ "-"+('0' + (lastSun.getMonth()+1)).slice(-2) + '-'+('0' + lastSun.getDate()).slice(-2);
	return dateString;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<input class="smalldatepicker" type="date" id="datepickerFrom" value="">
</input>
<label class="cccsfont"> to </label>
<input type="date" class="smalldatepicker" id="datepickerTo" value="">
</input>
</form>