0

i've been stuck on this problem for a while now and I am ready to pull my hair out :). I have to add a class to a span if a campaign date is expiring in 2 weeks or less. The date retrieved is a string in the following format

07/26/2017

when I run this function, I am passing the datestring as an argument since the method will be attached to the var which holds the string. But for whatever reason this logic isn't working. Am I totally screwing this up? It's failing silently somewhere. Thank you. I know it should be easy but I am caught in a loop.

campMethods.EndDateAlert = function (dateString) {
    var currentDate = new Date ();
    var twoWeeks = new Date ();
    twoWeeks.setDate(currentDate.getDate() + 14)
    var $EndDateSpan = $('.campaign-end-date');

    if (dateString <= twoWeeks) { 
        $EndDateSpan.addClass('red');
  }
    return dateString;
};
erics15
  • 567
  • 1
  • 7
  • 16

2 Answers2

1

Try comparing milliseconds of the dates. We know that there are 1000 * 60 * 60 * 24 * 14 = 1209600000 milliseconds in two weeks, knowing this we can add 1209600000ms to the current date and compare this to the milliseconds of the due date.

let dueDate = new Date('07/26/2017');

if(Date.now() + 1209600000 > dueDate.getMilliseconds()){
    //do stuff
}
Jrs.b
  • 61
  • 6
  • `getMilliseconds()` returns the number of milliseconds in the current time. You want `getTime()`. But this is also the answer from the proposed duplicate, so you're not doing yourself any favors by answering it. – Heretic Monkey Jun 30 '17 at 19:47
1

You can do that with some Math. The key is, 2 weeks = 14 days.

Here is Pure Javascript example for you:

var date = "07/26/2017".split("/");
var formatedDate = (date[2] + '' + date[0] + '' + date[1]);


var currentDate = new Date();

var today = currentDate.getFullYear() +''+ ("0" + (currentDate.getMonth() + 1)).slice(-2)+''+("0" + currentDate.getDate()).slice(-2); 

var compareDay = formatedDate - today;


if(compareDay < 14){// 14 day = 2 week
// do something for less than 2 weeks
console.log('Less than 2 weeks will be expired');
} else {
// also can do something
console.log('more than 2 weeks will be expired.');
}

Javascript Date Reference

Kamarul Anuar
  • 312
  • 4
  • 16