Forum Discussion

RachelHorton-2c's avatar
RachelHorton-2c
Community Member
2 years ago

JavaScript help needed - Add 6 months to a date

I'm looking for help with JavaScript. I have code to display the current date in MM/DD/YYYY format. I need to also display a date 6 months into the future. I am not skilled with JavaScript. Any help is appreciated.

This is the code I am using to display the current date where the variable is %DateValue%:

var currentDate = new Date()
var day = currentDate.getDate()
var month = currentDate.getMonth() + 1
var year = currentDate.getFullYear();
var player = GetPlayer();
var newName = month + "/" + day + "/" +year
player.SetVar("DateValue", newName);

All the best,
Rachel

  • SandeepGadam's avatar
    SandeepGadam
    Community Member

    Hello Rachel, here is the updated code to get the date for the next 6 months:

    var currentDate = new Date();
    currentDate.setMonth(currentDate.getMonth() + 6);

    var day = currentDate.getDate();
    var month = currentDate.getMonth() + 1;
    var year = currentDate.getFullYear();

    var player = GetPlayer();
    var newName = month + "/" + day + "/" + year;
    player.SetVar("DateValue", newName);

    You can use the setMonth method of the Date object to add 6 months to the current date and then we extract the day, month, and year of the new date and update the Date Value. Modifying the "+6" in the second line will get your desired future date.

  • Basically you just add the future day in your Date Object. Like this.

    var someFutureDate = new Date('11/21/2023');


    To format it as you want you have to repeat similar steps as you do in the above code.
    However you can use builtin functionality of the Date Object to format it too.

    I guess in the end you want to compare whether a date is past or not.
    For that you need to use getTime() of the Date Object. It translates any given Date to a number of milliseconds that have passed since Januari 1 1970. And thus you then can compare 2 dates...

    Like this.

    // Compare the two dates using getTime() method and check if the given date is in the past

    var currentDate  = new Date();
    var futureDate    = new Date('11/22/2024 12:30 PM');
    var pastDate       = new Date('11/21/2021 18:30 PM');

    if (futureDate.getTime() > currentDate.getTime()) {

    }
    if (pastDate.getTime() < currentDate.getTime()) {

    }

    getTime() returns a number like this 845337932000

     

    Adding a simple sample Story.