In this lesson, we will perform more complex operations with variables. We will also use new
concepts, such as conditional statements and loops.
Below this paragraph, you'll find a program that calculates the approximate amount of time
in between today's date and a date entered by the user.
-Line 1 starts with the creation of a text box. The box's type is set to "date",
meaning that only dates in the following format: MM/DD/YYYY can be input into the box.
The box is given the ID "myDate" which will be used later in our function.
-Line 3 contains the creation of a button. The onclick
command is set to call the function myFunction() whenever it is clicked.
-Lines 5 through 7 create three headers that will display variables from our function.
They are each given an ID that will be referenced later in our code.
-Line 14 creates a variable that will store the Date entered by the user.
In order to create a variable that stores a date, we need to utilize the command new Date().
Within the parentheses, we use the document.getElementById() command to retrieve the value
from text box "myDate". This value is then passed to our variable X.
-Line 16 creates a variable that stores today's date. When the new Date()
command is used without any values in the parentheses, it is set to today's date by default.
-Line 18 finds the difference between our two dates. In order to subtract them,
the dates need to be converted into numbers. We use the function Math.abs to
convert our dates into milliseconds, and then we subtract the user date from today's date.
-Line 20 creates the variables that will store our days, months, and years
once they are calculated.
-Line 24 starts with a for loop. For loops will continue to
execute the instructions within their brackets for a specified amount of times. The number of times
is determined by the parameters within its parentheses.
The parameters of a for loop are divided into three sections; these sections are divided with a semi-colon.
The first section var i = 0 starts with the creation of a variable named "i" that is set to zero.
The second section i < total_days tells our loop to execute while "i" is less than the variable "total_days".
The last section i++ will increment our variable "i" each time the loop finishes a cycle.
This ensures that "i" will eventually be equal to "total_days". If not for this final paramenter, our loop
would execute an infinite amount of times.
-Line 27 increments our variable "num_days". This will count the number of days in between dates.
-Lines 29 through 33 utilize an if statement to convert "num_days" to a month if it exceeds
the value of 31.
-Lines 29 through 33 utilize an if statement to convert "num_months" to a year if it exceeds
the value of 12.
-Lines 43 through 50 append our day, month, and year variables to their appropriate headers.
This allows them to be viewed by the user.