크롬 to-do list 앱 만들기 복습
:new Date () 이용하여 현재 시간 및 날짜 가져오기
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>현재 시간 가져오기</title>
</head>
<body>
<div>현재 시간</div>
<div class="js-clock">
<h2 class="amPm_text">AM</h2>
<h1 class="clock_text">12:00:00</h1>
</div>
<div class="js-date">
2020년 5월 14일 목요일
</div>
<script src="js/clock.js"></script>
<script src="js/date.js"></script>
</body>
</html>
현재 시간 가져오기
: new Date ( ) 활용
const clockContainer = document.querySelector(".js-clock"),
clockTitle = clockContainer.querySelector("h1"),
amPm = clockContainer.querySelector("h2");
function getTime() {
const time = new Date();
let hours = time.getHours(); // 변수가 변하기때문에, const로 선언하면 error 발생
const minutes = time.getMinutes();
const seconds = time.getSeconds();
if(hours >= 12) { // 시간이 12보다 클 떄, PM으로 변경 후, 12시간을 빼준다.
amPm.innerText = 'PM';
hours = hours - 12;
}
clockTitle.innerText = `${hours < 10 ? `0${hours}` : hours } :
${minutes < 10 ? `0${minutes}` : minutes} : ${seconds < 10 ? `0${seconds}` : seconds}`;
//시간이 10보다 작으면 시간 앞에 0을 붙히도록 삼항연산자를 이용하여 표현
}
function init() {
getTime();
setInterval(getTime, 1000); //1초 마다 getTime 함수 주기적으로 실행
}
init();
-new Date (); 현재 위치를 기준으로 현재 시간을 가져온다 .
-getHours () -> 현재 시간 가져오기
-getMinutes ();-> 현재 분 가져오기
-getSeconds (); -> 현재 초 가져오기
* 오전, 오후를 AM, PM으로 표현하고 24시간이 아닌 12시간 기준으로 시간을 표현하기
if(hours >= 12) { // 시간이 12보다 클 떄, PM으로 변경 후, 12시간을 빼준다.
amPm.innerText = 'PM';
hours = hours - 12;
}
if문을 사용하여 시간이 12시를 넘을 시에 조건을 걸어주었다.
12시가 넘을 때에는 "PM"으로 표시한다. 초기값이 AM 이기때문에 12시를 넘지않을 때에는 AM으로 표시된다.
12시간 기준으로 시간을 표시하기위해, 12시가 넘을 때에는 현재시간 - 12 를 해주었다.
여기서 겪었던 기초적인 문법 오류는 상단에서 hours 변수를 정의할 때 다른 변수와 동일하게 변수의 값이 변하지 않는 상수, const 으로 선언해주어서 hours = hours - 12 ; 부분에서 문법오류 발생하였다.. ㅎㅎ
변수 선언할 때 주의해야겠다..
*시간이 10보다 작을 때, 즉 한자리수 일 때 시간 앞에 0을 붙혀서 표현하기 (01시, 02시 ,,,,)
clockTitle.innerText = `${hours < 10 ? `0${hours}` : hours } :
${minutes < 10 ? `0${minutes}` : minutes} :
${seconds < 10 ? `0${seconds}` : seconds}`;
//시간이 10보다 작으면 시간 앞에 0을 붙히도록 삼항연산자를 이용하여 표현
(!)삼항연산자를 이용하였다.
- 삼항연산자 : 조건 ? A : B , 조건이 참이면 A를 실행하고, 거짓이면 B를 실행한다.
{hours < 10 ? `0${hours}` : hours ---> hours가 10보다 작으면 시간앞에 0을 붙히고, 그렇지 않으면 hours만 표현
*`${ }`: string은 백틱 ``으로 감싸주고, 변수는 ${}로 감싸주기
*현재 날짜 가져오기
const dateTitle = document.querySelector(".js-date");
function getDay() {
const today = new Date();
const years = today.getFullYear(); // 년도 가져오기
const months = today.getMonth() + 1; // 월 가져오기
const dates = today.getDate(); // 일 가져오기
const week = ['일요일', '월요일', '화요일', '수요일', '목요일', '금요일', '토요일'];
const days = week[today.getDay()]; // 요일 가져오기
dateTitle.innerText = `${years}년 ${months}월 ${dates}일 ${days}`
}
function init() {
getDay();
}
init();
- .getFullYear () ; , getMonth(); , getDate() 를 이용해서 년 월 일 가져오기
- getMonth() 의 경우 1월이 0 으로 표시되기때문에 + 1 를 해주었다.
- getDate()의 경우도 일요일 0, 월요일 1, ~~~, 금요일 5 이런식으로 표현되기때문에
미리 배열을 만들어 요일값을 넣어준다음, 표현하였다.
const days = week[today.getDay()];
'잡다한 메모' 카테고리의 다른 글
[JavaScript] 삼항연산자 (ternary operator) (0) | 2020.05.21 |
---|---|
[JavaScript] fetch API 이해과 개념 / .then() (0) | 2020.05.21 |
[JavaScript]현재 위치 가져오기 navigator API : geolocation.getCurrentPosition() (0) | 2020.05.15 |
Github-git push 실행시 오류 해결방법 (failed to push some refs to~) (0) | 2020.05.08 |
Github - git push 실행 시 오류 해결방법 ('origin' doest not appear to be a git repsitory) (0) | 2020.05.08 |