Reputation: 329
Hi I have scenario where I need to get quantity of books sold in last two weeks. I am using Javascript for that. Everything was working fine until today. Comparison is failing when day is friday. Below is the example.
//Function to get Monday of thisweek,last week and last to last week.
function GetMonday(mday) {
var today, todayNumber, mondayNumber, monday;
today = new Date();
todayNumber = today.getDay();
mondayNumber = mday - todayNumber;
return new Date(today.getFullYear(), today.getMonth(), today.getDate() + mondayNumber).toDateString();
}
var currDate = new Date().toDateString(); // gets todays date
var currwkDate = GetMonday(1); //Gets this week Monday's Date
var lastwkDate = GetMonday(-6); //Gets last week Monday's Date
var twowkDate = GetMonday(-13); //Gets Last to last week Monday's Date
var BillDate=new Date("09/04/2015").toDateString(); // Friday (04 Sep)
if (currDate == BillDate) {
alert("equal");
}
if (BillDate > currwkDate) {
alert("this week");
}
if (BillDate > lastwkDate) {
alert("last week");
}
if (BillDate > twowkDate) {
alert("two week")
}
Ideally above code should get three alert box(this week,last week,two week) buts its not giving even single alert.
If i edit above code and put BillDate to any other date which is not friday same code will work fine for example
var BillDate= new Date("09/03/2015").toDateString(); //Thursday 03-Sep
I am not sure what is the problem please help!!!!!
Upvotes: 1
Views: 52
Reputation: 21209
Your code is actually doing string comparisons rather than date comparisons. The reason this fails is because M
from Monday is less than T
, W
, and S
, but not F
.
This makes it so that BillDate > currwkDate
is only false if it's Friday. since F < M
. The fix is to compare dates instead (remove uses of toDateString
):
//Function to get Monday of thisweek,last week and last to last week.
function GetMonday(mday) {
var today, todayNumber, mondayNumber, monday;
today = new Date();
todayNumber = today.getDay();
mondayNumber = mday - todayNumber;
return new Date(today.getFullYear(), today.getMonth(), today.getDate() + mondayNumber);
}
var currDate = new Date(); // gets todays date
var currwkDate = GetMonday(1); //Gets this week Monday's Date
var lastwkDate = GetMonday(-6); //Gets last week Monday's Date
var twowkDate = GetMonday(-13); //Gets Last to last week Monday's Date
var BillDate=new Date("09/04/2015"); // Friday (04 Sep)
if (currDate.getYear() == BillDate.getYear() && currDate.getMonth() == BillDate.getMonth() && currDate.getDate() == BillDate.getDate()) {
alert("equal");
}
if (BillDate > currwkDate) {
alert("this week");
}
if (BillDate > lastwkDate) {
alert("last week");
}
if (BillDate > twowkDate) {
alert("two week")
}
Edit: The first check for dates to be equal also needs to be modified to only check year, month, and date (ignore hours/etc.).
Upvotes: 1