<< back to code examples

JavaScript Clock App

This JavaScript Clock App is written in JavaScript and a little JQuery using the built in Date object. More features will be added soon.

//Global Date Check (onload)
	var date = new Date();

	var thisYear = date.getFullYear();
	var num = date.getDate();
	var month = date.getMonth();
	var day = date.getDay();

	var hour = date.getHours();
	var min = date.getMinutes();
	var sec = date.getSeconds();
	var ms = date.getMilliseconds();


//check to see the time of day
	if (hour <= 10) {
		console.log('Good Morning');

	} else if (hour <= 16) {
		console.log('Good Afternoon');
	} else {
		console.log('Good Evening');
	}


//Arrays for converting index returned
	var weekDays = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
	var months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];

	//convert indexes to strings
	day = weekDays[day];
	month = months[month];

	var fullDate = day + ' ' + month + ' ' + num +', ' + thisYear;
	var print = document.getElementById('theDate');

	print.innerHTML = fullDate;


//the clock
	var clock = document.getElementById('clock');
	var timeOfDay = document.getElementById('timeOfDay');

	setInterval(function(){

		var dateClock = new Date();

		var thisYear = dateClock.getFullYear();
		var num = dateClock.getDate();
		var month = dateClock.getMonth();
		var day = dateClock.getDay();

		var hour = dateClock.getHours();
		var min = dateClock.getMinutes();
		var sec = dateClock.getSeconds();
		var ms = dateClock.getMilliseconds();

		var offset = dateClock.getTimezoneOffset();

		console.log('Offset = ' + offset);


		//if hour, min, sec is less than 10 add a leading 0
		if (hour < 10) { var zeroH = '0'; }  else { var zeroH = ''; }
		if (min < 10) { var zeroM = '0'; }  else { var zeroM = ''; }
		if ( sec < 10 ) { var zeroS = '0'; } else { var zeroS = ''; }

		var theTime = zeroH + hour + ' : ' + zeroM + min + ' : ' + zeroS + sec;

		clock.innerText = theTime;

//show different background every 30 seconds (testing only)
		if(sec > 0 && sec < 30) {
			$('body').removeClass('night').addClass('day');
			//happy.setAttribute('style','visibility:visible');
		} else {
			$('body').removeClass('day').addClass('night');
			//happy.setAttribute('style','visibility:hidden');
		}

	}, 1000);

More Code Projects