2

Ok!! I am trying to get date and month exactly 5 years ago from today's date in JQuery.

The main thing i am missing that i have to take care of leap years also and that i am struggling with.

I have tried below function

function printFiveYears()
{   
    var fiveYears = new Date();
    fiveYears.setTime(fiveYears.valueOf() - 5 * 365 * 24 * 60 * 60 * 1000);
    window.alert("5 years ago, the time and date were: " + fiveYears.toString());
}

But here, i am directly subtracting 365 days which is not right. Let me know corrections please.

Ps: No external plugins please.

Gags
  • 3,759
  • 8
  • 49
  • 96

2 Answers2

2

http://www.w3schools.com/js/js_date_methods.asp

var now = new Date();
var five_years_ago = new Date(now.getFullYear()-5,now.getMonth(),now.getDay());

And if you want, add to hours, minutes and seconds.

I hope it helps.

pabgaran
  • 773
  • 4
  • 15
  • does it take care of leap year? and i want only month date ad year.. not full timstamp – Gags May 13 '15 at 15:35
  • 1
    I see 2 issues with this answer. First, it does not take care of leap year. Second, `getDay()` method only returns the week day. So for today, 5/13/2015, get day will return you 3. You should use `.getDate()` method instead. – Caner Akdeniz May 13 '15 at 15:39
0
  $(function() {
            $('[type="date"]').prop('min', function() {
                return new Date().toJSON().split('T')[0];
            });

            $('[type="date"]').prop('max', function() {
                var myDate = new Date((new Date()).getTime() + (30 * 24 * 60 * 60 * 1000));
                var newDate = (myDate.toJSON().split('T')[0]);
                return newDate;
            });
        });
vino
  • 107
  • 1
  • 4