1

I have a date variable being set on my page like this:

startDate =  "03/28/2017";

How can I check if that date is 7 or less days before today's date?

It will need to be used in a conditional if statement.

user3390251
  • 317
  • 2
  • 5
  • 22

1 Answers1

3

You can try using moment.js,

var a = moment([2007, 0, 29]);
var b = moment([2007, 0, 28]);
a.diff(b) // 86400000

or even better, it has an inbuilt method, which says after how many days.

moment([2007, 0, 29]).toNow(); // in 4 years

and if you want to use old plain javascript :

var date1 = new Date("3/30/2017");
var date2 = new Date("3/23/2017");
var timeDiff = Math.abs(date2.getTime() - date1.getTime());
var diffDays = Math.ceil(timeDiff / (1000 * 3600 * 24)); 

If you want to compare with today

var date1 = new Date("3/23/2017")
var date2 = new Date();
Dave Ranjan
  • 2,966
  • 24
  • 55
  • Thank you @Dave - this would work except I would need date1 to populate dynamically though. Any ideas how date1 can dynamically set to today's date? – user3390251 Mar 30 '17 at 18:27
  • So, you want your date1 to be current date or something you'll get from server? – Dave Ranjan Mar 30 '17 at 18:31
  • Yes, the current date! – user3390251 Mar 30 '17 at 18:33
  • Please don't suggest parsing strings with a bulit-in parser (Date constructor and Date.parse), it should be done manually or with a library, see [*Why does Date.parse give incorrect results?*](http://stackoverflow.com/questions/2587345/why-does-date-parse-give-incorrect-results) – RobG Mar 30 '17 at 22:57