Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript: how to calculate the date that is 2 days ago? [duplicate]

Tags:

javascript

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.

like image 745
dat789 Avatar asked Dec 12 '12 11:12

dat789


People also ask

How can I get yesterday's date from a new date?

Use the setDate() method to get the previous day of a date, e.g. date. setDate(date. getDate() - 1) .

Can we subtract two dates in JavaScript?

Here, first, we are defining two dates by using the new date(), then we calculate the time difference between both specified dates by using the inbuilt getTime(). Then we calculate the number of days by dividing the difference of time of both dates by the no. of milliseconds in a day that are (1000*60*60*24).

How do you check if a date is after another date in JavaScript?

To check if a date is after another date, compare the Date objects, e.g. date1 > date2 . If the comparison returns true , then the first date is after the second, otherwise the first date is equal to or comes before the second.


2 Answers

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());
like image 154
RobG Avatar answered Sep 21 '22 16:09

RobG


You can do the following

​var date = new Date(); var yesterday = date - 1000 * 60 * 60 * 24 * 2;   // current date's milliseconds - 1,000 ms * 60 s * 60 mins * 24 hrs * (# of days beyond one to go back) yesterday = new Date(yesterday); console.log(yesterday);​ 

The Date is available as a number in miliiseconds, you take today subtract two days and create a new date using that number of milliseconds

like image 45
pfried Avatar answered Sep 22 '22 16:09

pfried