자바스크립트(Javascript) 입문 - 자바스크립트로 무슨 요일인지 나타내기
2021-08-13
자바스크립트 학습일지입니다.
해당 내용은 노마드코더님의 <바닐라JS로 크롬 앱 만들기> 강의를 들으며 추가적인 학습을 정리한 내용입니다.
이번 포스팅에선 요일 기능을 구현해봅시다.
저번 포스팅에서 자바스크립트를 통해 현재 날짜와 시간을 알아낼 수 있었습니다.
const clock = document.querySelector("h2#clock");
const todayDate = document.querySelector("#date")
function getClock() {
const date = new Date();
const hours = String(date.getHours()).padStart(2,"0");
const minutes =String(date.getMinutes()).padStart(2,"0");
const seconds = String(date.getSeconds()).padStart(2,"0");
const year = date.getFullYear(); // 년도
const month = date.getMonth() + 1; // 월
const dateday = date.getDate(); // 날짜
clock.innerText = `${hours}:${minutes}:${seconds}`;
todayDate.innerText = `${year}년 ${month}월 ${dateday}일`
}
getClock();
setInterval(getClock, 1000);
Date( ) 함수와, getHours( ) , getMinutes( ) , getSeconds( ) 를 통해 시간을 알 수 있습니다.
Date( ) 함수와, getFullyear( ) , getMonth( ) , getDate( ) 를 통해 날짜을 알 수 있습니다.
이를 innerText를 통해 브라우저에 나타냈습니다.
마찬가지로, Date( ) 함수와, getDay를 통해 요일을 알 수 있습니다.
콘솔 창을 열어 date.getDay()를 입력해봅시다.
위와 같이, 5가 뜹니다. 제가 작성하고있는 날은 금요일이고, getDay는 요일을 수로 표현합니다.
0은 일요일, 1은 월요일 ... 5는 금요일 6은 토요일입니다.
브라우저에 숫자가 아닌 요일로 나타내기위해 배열을 만들어, 수에 맞는 요일을 출력할 수 있습니다.
const week = new Array('일요일', '월요일', '화요일', '수요일', '목요일', '금요일', '토요일');
const day = date.getDay();
const todayLabel = week[day];
이를 통해 요일이 추가된 clock.js는 아래와 같습니다.
const clock = document.querySelector("h2#clock");
const todayDate = document.querySelector("#date")
function getClock() {
const date = new Date();
const hours = String(date.getHours()).padStart(2,"0");
const minutes =String(date.getMinutes()).padStart(2,"0");
const seconds = String(date.getSeconds()).padStart(2,"0");
const year = date.getFullYear(); // 년도
const month = date.getMonth() + 1; // 월
const dateday = date.getDate(); // 날짜
const week = new Array('일요일', '월요일', '화요일', '수요일', '목요일', '금요일', '토요일');
const day = date.getDay();
const todayLabel = week[day];
clock.innerText = `${hours}:${minutes}:${seconds}`;
todayDate.innerText = `${year}년 ${month}월 ${dateday}일 ${todayLabel}`
}
getClock();
setInterval(getClock, 1000);
출처
Date.prototype.getDay() - JavaScript | MDN
The getDay() method returns the day of the week for the specified date according to local time, where 0 represents Sunday. For the day of the month, see Date.prototype.getDate().
developer.mozilla.org
노마드 코더 Nomad Coders
코딩은 진짜를 만들어보는거야!. 실제 구현되어 있는 서비스를 한땀 한땀 따라 만들면서 코딩을 배우세요!
nomadcoders.co