Reputation: 321
I want my code to work like, If I select anydate of a week, it will return me the date of the previous monday of that week. for example: if I select 8th jan, 2013, It will automaticaly return 7th jan, 2013. Here is my code:
var dateValue = document.getElementById("OurDate").value; //OurDate is the textbox where I am giving the date as input
var d = new Date(dateValue);
var newDate = new Date(); ;
var day = d.getDay();
if (day == "0")
newDate.setDate(d.getDate() - 6);
else if (day == "1")
newDate = d;
else if(day=="2")
newDate.setDate(d.getDate() - 1);
else if(day=="3")
newDate.setDate(d.getDate() - 2);
else if(day=="4")
newDate.setDate(d.getDate() - 3);
else if(day=="5")
newDate.setDate(d.getDate() - 4);
else if (day == "6")
newDate.setDate(d.getDate() - 5);
alert(newDate);
This code is working fine for any date in January. But when Im giving any date in Feb or any other month. Its showing me the date of January. for example: if I select 19th feb,2013 it should return 18th feb,2013 but its returning 18th jan,2013. Any help to this problem? Thanks in advance
Upvotes: 1
Views: 169
Reputation: 298226
Instead of getDate()
, use getDay()
:
The value returned by
getDay
is an integer corresponding to the day of the week: 0 for Sunday, 1 for Monday, 2 for Tuesday, and so on.
You can then just use .setDate()
to set the date:
var date = new Date();
var day = date.getDay();
var days_from_monday = day - 1;
date.setDate(date.getDate() - days_from_monday);
Or more compactly:
var date = new Date();
date.setDate(date.getDate() - date.getDay() + 1);
Upvotes: 1
Reputation: 136124
The problem is really in this line:
var newDate = new Date();
By not supplying any value in the constructor of Date
it uses today's date. So you're subtracting from today.
If you construct both d
and newDate
in the same way, it works as expected:
var d = new Date('2013-02-19');
var newDate = new Date('2013-02-19');
Live example: http://jsfiddle.net/cS2CC/
Upvotes: 1
Reputation: 47099
It's because of you are making a new Date object instead of working on the same or cloning it:
var d = new Date(dateValue);
var newDate = new Date( +d ); // Cloning d
You can rewrite your whole statement to:
var date = new Date();
date.setDate( date.getDate() - date.getDay() + 1 );
console.log( date.getDay() ); // 1
Upvotes: 2