Currently, I am working on developing a JavaScript file to create variables for dates and times using the shortcut method. Although everything seems to be in order from what I can see, it does not display correctly, and when checked with Google Chrome's debugger, it shows an error message:
[Uncaught TypeError: Cannot Read 'firstChild' of null]
This is the code snippet that I have written:
function mdy(){
var
h = new Date(),
year = h.getFullYear(),
month = h.getMonth() + 1,
day = h.getDate();
if(month < 10) { month = "0" + month; }
if(day < 10) { month = "0" + month; }
var string = month + "/" + day + "/" + year;
document.getElementById('mdy').firstChild.nodeValue = string;
}
function ymd(){
var
h = new Date(),
year = h.getFullYear(),
month = h.getMonth() + 1,
day = h.getDate();
if(month < 10) { month = "0" + month; }
if(day < 10) { month = "0" + month; }
var string = year + "/" + month + "/" + day;
document.getElementById('ymd').firstChild.nodeValue = string;
}
var $date = {
mdy: '<span id="mdy"> </span>',
ymd: '<span id="ymd"> </span>'
}
/* $time module */
// this comes in two formats, standard and military.
// type $time.standard for standard time and $time.military
// for military time
function tstandard(){
var
h = new Date(),
hours = h.getHours(),
minutes = h.getMinutes();
minutes = ( minutes < 10 ? "0" : "" ) + minutes;
var diem = ( hours < 12 ) ? "am" : "pm";
hours = ( hours > 12 ) ? hours - 12 : hours;
hours = ( hours == 0 ) ? 12 : hours;
var string = hours + ":" + minutes + " " + diem;
document.getElementById("tstandard").firstChild.nodeValue = string;
}
function tmilitary() {
var
h = new Date(),
hours = h.getHours(),
minutes = h.getMinutes();
minutes = ( minutes < 10 ? "0" : "" ) + minutes;
hours = ( hours == 0 ) ? 12 : hours;
if(hours < 10) { hours = "0" + hours }
var string = hours + ":" + minutes;
document.getElementById("tmilitary").firstChild.nodeValue = string;
}
var $time = {
standard: "<span id='tstandard'> </span>",
military: "<span id='tmilitary'> </span>"
}
/*! universal body onload function !*/
window.onload = function(){
mdy(); setInterval('mdy()', 1000);
ymd(); setInterval('ymd()', 1000);
tstandard(); setInterval('tstandard()', 1000);
tmilitary(); setInterval('tmilitary()', 1000);
}
In my HTML file, I have included the following script:
<script>document.write($date.mdy + " - " + $time.standard);</script>