Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if a date within in range

I am trying to check if a date of format mm.dd.yyyy is greater than today and less than the date after 6 months from today.

Here is my code:

var isLinkExpiryDateWithinRange = function(value) {
    var monthfield = value.split('.')[0];
    var dayfield = value.split('.')[1];
    var yearfield = value.split('.')[2];
    var inputDate = new Date(yearfield, monthfield - 1, dayfield);
    var today = new Date();     
    today = new Date(today.getFullYear(), today.getMonth(), today.getDate());
    alert(inputDate > today);//alert-> true
    var endDate = today;
    endDate.setMonth(endDate.getMonth() + 6);
    alert(inputDate > today);//alert-> false
    if(inputDate > today && inputDate < endDate) {
        alert('1');
    } else {
        alert('2');/always alert it
    }
}

If I execute isLinkExpiryDateWithinRange('12.08.2012') I wish it will show 1 as this is within the range, but it is displaying 2. Moreover the first alert is showing true and the second one false.

Can anyone please explain what is happening?

like image 385
Tapas Bose Avatar asked Nov 08 '12 15:11

Tapas Bose


People also ask

How do you find if a date is within a range JavaScript?

var dateFrom = "02/05/2013"; var dateTo = "02/09/2013"; var dateCheck = "02/07/2013"; var from = Date. parse(dateFrom); var to = Date. parse(dateTo); var check = Date. parse(dateCheck ); if((check <= to && check >= from)) alert("date contained");


1 Answers

Change:

var endDate = today;

to:

var endDate = new Date(today);

See the posts here for how objects are referenced and changed. There are some really good examples that help explain the issue, notably:

Instead, the situation is that the item passed in is passed by value. But the item that is passed by value is itself a reference.

JSFiddle example

like image 176
Chase Avatar answered Sep 30 '22 05:09

Chase