Date 객체를 이용한 디지털 시계
14 Oct 2021 -
1 minute read
Date 객체
let date = new Date(year, monthIndex, day, hours, minutes, seconds, milliseconds);
-
getFullYear() : 4자리 ‘연도’ 값 반환
-
getMonth() : ‘월’ 반환
- 1월 = 0 (0~11)
-
getDate() : ‘일’ 반환
-
getDay() : ‘요일’ 반환
- 0 = 일요일 ~ 6 = 토요일
-
getHours() : ‘시간’ 반환
-
getMinutes() / getSeconds() / getMilliseconds()
Date 객체를 이용해 디지털 시계 만들기
See the Pen Untitled by Jinsol (@losuif) on CodePen.
HTML
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>디지털 시계</title>
</head>
<body>
<div id="wrap">
<div id="calendar">
<span id="nowTime"></span>
<br>
<span id="nowDate"></span>
</div>
</div>
<!-- div#wrap -->
</body>
</html>
CSS
#wrap {
width: 400px;
height: 100px;
background-color: rgb(52, 52, 52);
margin: 20px auto;
padding: 20px;
user-select: none;
}
span {
font-size: 50px;
color: #fff;
}
#nowDate {
font-size: 20px;
color: rgb(148, 205, 255);
}
JavaScript
function fnDigitalClock(){
let now = new Date();
let prnTime = now.toLocaleTimeString();
document.getElementById("nowTime").innerText = prnTime;
let year = now.getFullYear();
let month = now.getMonth()+1;
let date = now.getDate();
let day = now.getDay(); //일요일=0 ~ 토요일=6
let dayArr = ["일", "월", "화", "수", "목", "금", "토"]
let prnDate = year + "년 " + month + "월 "
+ date + "일 " + dayArr[day] + "요일";
document.getElementById("nowDate").innerText = prnDate;
}
setInterval(fnDigitalClock, 1000);