JavaScript로 만나이계산해보자!

JD·2021년 9월 28일
0

JavaScript

목록 보기
5/13

생일을 입력 받고 만 나이를 구해보자

💌만나이계산

function toAge(birth) {
	let regex = /(\.)|(\-)|(\/)/g;
	birth = birth.replace(p,"");
	
	if(!isValidDateFormat(birth)) throw '기본날짜형식이 올바르지않습니다';
	
	let y,m,d;
	
	y = parseInt(birth.substr(0,4));
	m = parseInt(birth.substr(4,2));
	d = parseInt(birth.substr(6));
	
	let bdate = new Date(y,m-1,d);
	
	let now = new Date();
	
	let age = now.getFullYear() - bdate.getFullYear();
	
	
	// 만나이를 떄문에 조건을 건다
	if(bdate.getMonth() > now.getMonth()|| 
			(bdate.getMonth()==now.getMonth() && bdate.getDate()>now.getDate())){
		age--;
	}
	
	return age;
	
}

💌 쓰면서

만나이 때문에 조건을 건 부분이 조건이 너무 길다
다른방법이 없나 생각 해보자

💌 마치며

이젠 만나이를 해도 20대 중반이네....

0개의 댓글

Powered by GraphCDN, the GraphQL CDN