Most of the time developers used to play around with Date manipulations and end up in a total mess because many of them always have confusions in converting or formatting date times.
The pain of dealing with date times usually end up in long hours to complete a small task. So here is yet another JavaScript utility function to check whether the date occurs in the current week.
Seems to be simple isn’t it? Yes its simple, we have to find out the first and last day of the current week and to check whether the selected date lies in between these two days. But there is small tricky part. If the week consists of two different month always the first day(28 in 28-7-2013) will be greater than the last day of the week.(3 in 3-8-2013).How to deal with that?
Here is the approach to achieve the functionality.
function CheckDate() {
//seldate is the selected date from UI.
var seldate = document.getElementById('<%=txtDate.ClientID %>').value;
var curr = new Date(); // get current date
//Finding the first day & last day of the week using the current date & day
//getday() returns the day of the week.eg:if its Thursday ,getday() returns 4.
var first = curr.getDate() - curr.getDay();
var firstday = new Date(curr.setDate(first));
var lastday = new Date(curr.setDate(firstday.getDate() + 6));
//Forming the From date and To date.Using the getMonth() function we will be able to find the Month of the dates.So we will be able catch if months fall in different months also.
var from = Date.parse(firstday.getMonth() + 1 + "/" + firstday.getDate() + "/" + firstday.getFullYear());
var to = Date.parse(lastday.getMonth() + 1 + "/" + lastday.getDate() + "/" + lastday.getFullYear());
//Finally,Checking the date.
var checkDt = Date.parse(seldate);
if ((checkDt <= to && checkDt >= from)) {
alert('Selected date is on current week');
}
else {
alert('Selected date is not on current week');
}
return false;
}
Tip: This same function can be modified to check whether the date is between two particular dates or in a particular week.