I’m a total newbie and I’m confused about this tutorial. I know (at least I think I know) that the functions getDate and get Month and getFullYear are pre-set functions determined by JavaScript.
Why are those preset functions necessary for this tutorial if a new Date (2000,0,1) is being submitted as an argument to formatDate? Does getDate clash somehow with the numbers submitted as an argument?
In function pad, I understand that “number” checks to see whether a number is less than 10 and, if so, adds a zero, but what is the argument submitted to function pad? How does it get the numbers to check?
Can you please take me through (using plain language) this tutorial step by step…thank you in advance
function formatDate(date) {
function pad(number) {
if (number < 10)
return "0" + number;
else
return number;
}
return pad(date.getDate()) + "/" + pad(date.getMonth() + 1) +
"/" + date.getFullYear();
}
print(formatDate(new Date(2000, 0, 1)));
This function formats and prints the date.
The pad function is to add a “0” (not to add 10 as you noted) in front of a number that is less than 10.
This allows you to print a date in the dd/mm/yyyy format.
Eg. Feb 3, 2011 will be printed as 03/02/2011 instead of 3/2/2011
Within the formatDate function, the last line is return pad(….
the “pad” function in the “formatDate” function takes each date part and sends it to the padding function to prepend a “0” to ensure the mm/dd is followed instead of possibly sending a single digit variable – such as 3/2/2011
Hope that helps clarify things.
This line:
gets converted to (assuming a date of 23/2/2011)
This calls pad(23) – and the 23 is substituted into the “number” variable in the pad function. No change is required and 23 is returned.
pad(1+1) = pad(2) – and 2 is substituted into the “number” variable in the pad function. It appends a “0” and returns “02”
So, the final conversion is
and it ends up printing “23/02/2011”.