javascriptdate

Add A Year To Today's Date


I am trying to add a year to today's date. I am working in a system that does not allow you to use standard JavaScript.

For instance, to get today's date I have to use:

javascript:now();

I have tried:

javascript:now(+1);

I have never seen this before, but am in need of adding one year to today's date...

Has anyone seen getting current date this way before? And if so, how could I add a year?


Solution

  • You can create a new date object with todays date using the following code:

    var d = new Date();
        console.log(d);
    // => Sun Oct 11 2015 14:46:51 GMT-0700 (PDT)

    If you want to create a date a specific time, you can pass the new Date constructor arguments

     var d = new Date(2014);
        console.log(d)

    // => Wed Dec 31 1969 16:00:02 GMT-0800 (PST)
    

    If you want to take todays date and add a year, you can first create a date object, access the relevant properties, and then use them to create a new date object

    var d = new Date();
        var year = d.getFullYear();
        var month = d.getMonth();
        var day = d.getDate();
        var c = new Date(year + 1, month, day);
        console.log(c);

    // => Tue Oct 11 2016 00:00:00 GMT-0700 (PDT)
    

    You can read more about the methods on the date object on MDN

    Date Object