Advancing Date Using Javascript

Jun 04, 2018

Hi there, 

 

Looking to create JavaScript where the date will automatically advance (and roll over to the next month) when user advances to the next slide. The date will track how many days the learner has spent on their learning journey. Not sure what code will work to get this to advance...have already looked at a few discussions that insert the current date, but i need a given date to advance one day per slide. 

 

Thanks!

1 Reply
OWEN HOLT

The JavaScript you likely found probably looked something like this:

//declare a variable and assign the date object to it with today's date.
var today = new Date();

In JavaScript, an object is sort of like a file folder with labels and associated values.  The Date object holds things like the days of the week, months in the year, hours in the day, etc.  You can use an object to locate and manipulate specific values in the object.

To get the calendar day in the Date object, you use the Date label.  You've probably seen it in code looking something like this:

//get the day from the date object
var day = today.getDate();

If I just write and execute this code in the developer tools window of my browser and log the values to the console, it looks something like the following: 
var today = new Date();
console.log(today);
var day = today.getDate();
console.log(day);
> Tue Jun 05 2018 12:46:36 GMT-0500 (Central Daylight Time)
> 5

To manipulate this, I can write over the value stored on my date object from the computer date, to the day + 1.


//set the date in the date object to it's current date value plus 1 day
today.setDate(today.getDate()+1);

Now I can reset my day variable and look at the values in the log.
Putting it all together to see it in action, copy and execute this code in the developer tools window of your browser. Executing this:
var today = new Date();
console.log(today);
var day = today.getDate();
console.log(day);
today.setDate(today.getDate()+1);
console.log(today);
var day = today.getDate();
console.log(day);


Will return something like this:
> Tue Jun 05 2018 12:54:10 GMT-0500 (Central Daylight Time)
> 5
> Wed Jun 06 2018 12:54:10 GMT-0500 (Central Daylight Time)
> 6

I hope this helps, I tried to do more than just post the code but also provide some context and understanding.

This discussion is closed. You can start a new discussion or contact Articulate Support.