0

I am trying to retrieve a date but I am struggling with the month because January = 0 instead of 1. I need to retrieve items which occured after today -60 days.

 var today = new Date();
 if (today.getMonth() < 1) {
     var numberOfDaysLastMonth = getDaysInMonth(12,today.getFullYear()-1);    //number of days in december last year
     var numberOfDaysThisMonth = getDaysInMonth(today.getMonth()+1,today.getFullYear());  //number of days this month
} else {
    var numberOfDaysLastMonth = getDaysInMonth(today.getMonth(), today.getFullYear());    //number of days last month
    var numberOfDaysThisMonth = getDaysInMonth(today.getMonth()+1, today.getFullYear());  //number of days this month
};

var startDate = new Date();
var myMonth;
var myYear;

if (today.getMonth() < 1) {
   myMonth = today.getMonth() + 1;
    myYear = today.getFullYear()-1;
} else {
    myMonth = startDate.getMonth()-1;
myYear = today.getFullYear();
};

startDate  = myYear+"-"+myMonth+"-"+startDate.getDate();  // returns last month

Is there a more simple (and working) way to do this?

Niels V
  • 1,005
  • 8
  • 11
Marco
  • 85
  • 1
  • 14
  • `myMonth = today.getMonth() + 1` this solves your "January = 0 instead of 1" problem, right? To get time from today -60 days: `new Date(new Date().getTime() - 86400000 * 60).toISOString()` hope this helps in some way. :) – Barskey Feb 05 '18 at 12:19
  • Indeed. And using that code I can skip a lot of other code as well. for instance I don't need to define the myMonth and MyYear. All I could do is count the days in the month of last month and the month befor that together. So I could use that number instead of 60. – Marco Feb 05 '18 at 12:52
  • @Barskey—not all days have 24 hrs where daylight saving is observed, far better to subtract 60 days using `today.setDate(today.getDate() - 60)`. – RobG Feb 05 '18 at 21:32
  • @Marco—if you want the same date 2 months ago, use `date.setMonth(date.getMonth() - 2)`. May need a slight adjustment where 2 months ago was February or the current date is 31 but 2 months ago only had 30 days, for a fix see [*Adding months to a Date in JavaScript*](https://stackoverflow.com/questions/12793045/adding-months-to-a-date-in-javascript/12793246#12793246). – RobG Feb 05 '18 at 21:34

1 Answers1

0

If it's difficult to use dates as they are in Javascript, then modify them to work as they want them to work. An example:

Date.prototype.getMyMonth = function() {return this.getMonth() + 1;};

Now, you can change your code to use .getMyMonth instead of .getMonth.

Lajos Arpad
  • 64,414
  • 37
  • 100
  • 175