Wednesday, June 5, 2024
 Popular · Latest · Hot · Upcoming
186
rated 0 times [  193] [ 7]  / answers: 1 / hits: 141372  / 12 Years ago, wed, december 12, 2012, 12:00:00

Possible Duplicate:

Subtract days from a date in javascript






I have got a JavaScript that basically returns a date that is 2 days ago. It is as follows:



var x;
var m_names = new Array(January, February, March,
April, May, June, July, August, September,
October, November, December);

var d = new Date();
var twoDaysAgo = d.getDate()-2; //change day here
var curr_month = d.getMonth();
var curr_year = d.getFullYear();
var x = twoDaysAgo + - + m_names[curr_month] + - + curr_year;

document.write(x);


Assuming today is 12-December-2012, the above will return the date 10-December-2012. I don't think this will work dynamically as we move forward into a new month, OR, change the day from -2 to -15. It will work only from the 3rd of the month.



How can I modify this so when it is 12-December-2012 today and I want it to return me the date 15 days ago it should be 27-November-2012... and not -3-December-2012?



Any help appreciated. Thanks!
I'm a Javascript newbie.


More From » javascript

 Answers
64

If you have a date object, you can set it to two days previous by subtracting two from the date:





var d = new Date();
d.setDate(d.getDate() - 2);
console.log(d.toString());

// First of month
var c = new Date(2017,1,1); // 1 Feb -> 30 Jan
c.setDate(c.getDate() - 2);
console.log(c.toString());

// First of year
var b = new Date(2018,0,1); // 1 Jan -> 30 Dec
b.setDate(b.getDate() - 2);
console.log(b.toString());




[#81474] Monday, December 10, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
leighamarleem

Total Points: 75
Total Questions: 121
Total Answers: 111

Location: Norway
Member since Mon, May 23, 2022
2 Years ago
;