-1

everyone! I was looking for solution of this for a long time and didn't find anything.

I need to make element on page which will have +=2000 every month from ..let's say today's date. And I am puzzled without any idea how to do this. I easily wrote updating value every 10 seconds, but what about months that have different length and so on?

Should I compare difference between current date and today's date, than do +=2000*numberOfMonths? Then how often should I check if month has passed no to kill speedload?

Or is there any other convinient way to do it?

I know the solution might be easy, but I don't get it. Will be gratefull for any suggestions.

1 Answers1

1

You can do it like:

  const getMonthsPassed = () => {
    const startDate = new Date(2018, 10, 22); // month start at 0
    const currentDate = new Date();
    const monthDifference =
      (currentDate.getFullYear() - startDate.getFullYear()) * 12 +
      (currentDate.getMonth() - startDate.getMonth());
    return monthDifference;
  };
Cecil
  • 261
  • 2
  • 5
  • Hmm, but what about how often should I check this and than update value? How to set for example "Let's check this const value every week, maybe the new month is here?" – Anna Polyakova turnhandup Nov 22 '18 at 19:23
  • 1
    I think i have misunderstood the requirement. You want to have a month counter element, and for it to update the number of months since today? On the web you would expect to only need to run this once on page load. Although I suppose you can run a timeout function every minute to check if it's absolutely essential – Cecil Nov 22 '18 at 19:27
  • Yeah, you're absolutely right. Sorry, I am just starting with JS) Thank you a lot for the answer, it's elegant. Marked as the right one! – Anna Polyakova turnhandup Nov 22 '18 at 19:40