Building a CMS - The Application
(Page 3 of 5 )
We're not done once these values are stored however. If we want to display the date and time in a format that looks like the date below,
we will have to do some work on the numbers and add some text such as the "PM" to get what we need. The code below will get and display the date and time in this format. It can be called on document load. The form's name is set to release and each field is named year, month, day and hours respectively.
//Begin our function
var curr_dt = new Date();//create a new date object
//get the year, convert it to a string and then extract the last two characters
document.release.year.value = curr_dt.getFullYear().toString().substr(2,2);
//getMonth gives you 0-11 so add 1
document.release.month.value = curr_dt.getMonth() + 1;
document.release.day.value = curr_dt.getDate();
var hours = curr_dt.getHours();
var minutes = curr_dt.getMinutes();
The hours will take a little more work. Midnight comes up as 0; we will need to substitute this with 12 and tack on a "AM." If the number is above 12 we will need to subtract 12 from the number to start with 1 PM and go up to 11 PM, and if the number is 12 we need to also have a "PM" at the end but otherwise leave the number alone. Also, the minutes will not always be 2 digits. We will need to have a 01, 02, 03 type of format for them. All this means using a few "if" constructs.
//if minutes are 1-9 we need a leading zero
if(minutes < 10)
minutes = "0" + minutes;
//new day starts unless you are a programmer
if(hours == 0)
document.release.time.value = 12 + ":" + minutes + " AM";
//the noon hour is here so tack on a PM
else if(hours = 12)
document.release.time.value = hours + ":" + minutes + " PM";
//we are past noon. subtract 12 to start at 1 and go up.
document.release.time.value = (hours - 12) + ":" + minutes + " PM";
document.release.time.value = hours + ":" + minutes + " AM";
That was a lot to go through, but now we have a properly formatted date and time. This sets the default value for the fields when the page loads. If the user wants to change it they can.
More Web Hosting How-Tos Articles
More By Chris Root