[JS] new Date()를 이용한 시작일~마감일 사이모든날짜 배열에 담기

Park Bumsoo·2022년 6월 4일
0

프로젝트 중 시작일과 마감일 사이의 모든 일정을 출력받아와야하는 상황이 나왔다.

고민하던 중 toISOString(), split() 메서드와
setDate(), getDate()를 이용하여함수를 만들어 봤다.

function getDates() {
  
	const dateArray = [];
	let startDate = new Date(1654387200000);
  	let endDate = new Date(1656198000000);
  
	while(startDate <= endDate) {
		dateArray.push(startDate.toISOString().split('T')[0]);
		startDate.setDate(startDate.getDate() + 1);
	}
	return dateArray;
}

getDates() 

아래의 출력결과처럼 5~25일 까지의 모든 날짜를 받아올 수 있다.

출력결과
[ '2022-06-05', '2022-06-06', '2022-06-07', '2022-06-08', '2022-06-09', '2022-06-10',
'2022-06-11', '2022-06-12', '2022-06-13', '2022-06-14', '2022-06-15', '2022-06-16', 
'2022-06-17', '2022-06-18', '2022-06-19', '2022-06-20', '2022-06-21', '2022-06-22',
'2022-06-23', '2022-06-24', '2022-06-25' ]
profile
프론트엔드 주니어 개발자(React, Next.js)

0개의 댓글