### 날짜 객체에 number를 인자값으로 입력할 경우, month를 index로 인식한다.
아래의 예를 보자.
// bad let now = new Date(2019, 12, 1); console.log(now.getFullYear()); // 2020 console.log(now.getMonth()); // 0
getMonth는 index값은 0으로 시작해서 11로 끝난다. 다시 말해서, 1월의 index값은 0, 12월의 index값은 11이다.
컴퓨터는 위의 코드에서 12를 index로 인식하여, 11의 다음 index값인 0을 반환했다. 해가 넘어간 것으로 인식한 것이다. 그 결과, getFullYear에서도 2019가 아닌 2020이 반환되는 것을 확인할 수 있다.
이를 개선하기 위해서는 string을 인자값으로 넣으면 된다.
// good let now = new Date("2019, 12, 1"); console.log(now); console.log(now.getFullYear()); // 2019 console.log(now.getMonth()); // 11
원하는 결과가 나오는 것을 확인할 수 있다.
아래의 글은 wecode에서 공부하며 처음으로 5시간가량 붙잡고 씨름한 문제다. 풀이 과정에 대해 기억하려고 기록으로 남긴다.
function getWesternAge(birthday) { let now = new Date(); let age = now.getFullYear() - birthday.getFullYear(); let month = now.getMonth() - birthday.getMonth(); let date = now.getDate() - birthday.getDate(); if(month < 0) { return age - 1; } else if(month === 0 && date < 0) { return age - 1; } else { return age; } } // month < 0 // 생일 아직 안지남 // age - 1 // month > 0 // 생일 지남 // age // month = 0 // 모름 // date체크 // // date < 0 // 생일 안지남 // age - 1 // // date = 0 // 생일 // age // // date > 0 // 생일 지남 // age
console.log(Math.floor(-3.5)); // -4
console.log(Math.trunc(-3.5)); // -3