본문 바로가기

Document Room

Javascript로 만든 현재 시간 (실시간)

time.js

function clock() {
	var time = document.getElementById("time");	// id="time"

	var now = new Date();
		var year = now.getFullYear();		// FullYear=2020, Year=120 (2020 standard)
		var month = now.getMonth()+1;		// 0~11 to 1~12
		var date = now.getDate();
		var day = now.getDay();			// day=0~6
			var week = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];	// 0~6 to day of the week
		var hours = now.getHours();		// 24-hour format
		var minutes = now.getMinutes();
		var seconds = now.getSeconds();

	if(hours < 12) {				// AM, PM
		var ap = 'AM';
	}else{
		var ap = 'PM';
	}

	if(hours > 12) {				// if the time is PM, hours-12
		hours = hours-12;
	}


	// All make to two digits

	if(month < 10) {
		month = '0' + month;
	}

	if(date < 10) {
		date = '0' + date;
	}

	if(hours < 10) {
		hours = '0' + hours;
	}

	if(minutes < 10) {
		minutes = '0' + minutes;
	}

	if(seconds < 10) {
		seconds = '0' + seconds;
	}


	time.innerHTML = week[day] + ", " + month + "/" + date + "/" + year + "<br>" + hours + ":" + minutes + ":" + seconds + " " + ap;	// Insertion content

	setTimeout("clock()",100);			// Repeat every 100ms(0.1seconds)

}

window.onload = function() {				// Insert after Load
	clock();					// 's list
}

 

결과 :

 

time.js
0.00MB

막 가져다 쓰세요