만으로 계산한 나이를 구하는 함수인 getWesternAge 함수를 구현.
조건
이 함수는 birthday 라는 인자를 받습니다.
이 birthday 는 Date 객체 입니다. birthday 라는 인자를 넣었을 때,
현재를 기준으로 만으로 계산한 나이를 리턴 해주세요.
birthday 는 string이 아닌 Date 객체라는 걸 명심하세요
예를 들어, 오늘이 2021년 7월 21일이고, birthday 값이 다음과 같다면:
-> 1990-03-21T00:45:06.562Z
리턴 값은 31 이 되어야 합니다.
function getWesternAge(birthday) {
let today = new Date();
let birthDay = new Date(birthday);
let age = today.getFullYear() - birthDay.getFullYear();
//조건이 맞으면 age가 내려가게 해주면 된다.
nowMonth = today.getMonth()+1;
birthMonth = birthDay.getMonth()+1;
let month = nowMonth - birthMonth;
if(nowMonth > birthMonth || month === 0){//생일을 지났거나, 같은 날이라면
age;
} else {
age--;
}
return age;
}
console.log(getWesternAge('1990-03-21T00:45:06.562Z'));
let today = new Date();
let birthDay = new Date(birthday);
let age = today.getFullYear() - birthDay.getFullYear();
현재를 기준으로 만으로 계산한 나이를 구해야 한다.
만 나이라는 게 정해진 생일이 되거나, 생일을 지나야
원래 나이의 +1을 해주는 건데 이 조건을 충족시켜줘야
만 나이를 구할 수 있다.
let nowMonth = today.getMonth() +1;
let birthMonth = birthDay.getMonth() +1;
let month = nowMonth - birthMonth;
문제를 풀던 중 특이한 점을 발견했다.
바로 getMonth()이다.
날짜를 구하는 다른 get 메서드들과 다르게
+1을 해줘야 정상 날짜로 출력되기 때문이다.
ex)참고로 오늘은 21년 10월 10일이다.
let today = new Date();
let todayMonth = today.getMonth();
// 지금 todayMonth는 9로 나온다.
+ 1 을 안해주면 전 달만 계속 나올거다.
그러니까 getMonth()에는 항상 +1을 해줘야 한다는 사실 잊지 말자.
4. 만 나이에 해당하는 조건이면 기존 나이를 반환하고,
만 나이에 해당이 안되면 나이를 한 살 까주면 된다.
if(nowMonth > pastMmonth || month === 0) {
return age;
} else {
return age-1; or age--;// 이건 자기 스타일대로 고르면 된다.
function getWesternAge(birthday) {
let today = new Date();
let birthDay = new Date(birthday);
let age = today.getFullYear() - birthDay.getFullYear();
let nowMonth = today.getMonth() +1;
let birthMonth = birthDay.getMonth() +1;
let month = nowMonth - birthMonth;
if(nowMonth > pastMmonth || month === 0) {
return age;
} else {
return age-1; or age--;
}
return age;
}