# [PS] 남은 시간 계산하기

doongdoong·2일 전
0

## 문제

남은 시간을 일, 시, 분, 초로 표현해보자.

## 풀이

const SECOND = 1000;
const MINUTE = 60000;
const HOUR = MINUTE * 60;
const DAY = HOUR * 24;

function getDistance(currentDate, endDate) {
// getDistance 함수를 구현하세요
const currentDateObj = new Date(currentDate);
const endDateObj = new Date(endDate);

const diffMills = endDateObj.getTime() - currentDateObj.getTime();

const diffDay = Math.floor(diffMills / DAY);
const diffHour = Math.floor((diffMills - diffDay * DAY) / HOUR);
const diffMinute = Math.floor(
(diffMills - diffDay * DAY - diffHour * HOUR) / MINUTE
);
const diffSecond = Math.floor(
(diffMills - diffDay * DAY - diffHour * HOUR - diffMinute * MINUTE) / SECOND
);

let result = [];
if (diffDay > 0) {
result.push(${diffDay}일); } if (diffDay > 0 || diffHour > 0) { result.push(${diffHour}시);
}

if (diffDay > 0 || diffHour > 0 || diffMinute > 0) {
result.push(${diffMinute}분); } if (diffDay > 0 || diffHour > 0 || diffMinute > 0 || diffSecond > 0) { result.push(${diffSecond}초);
}

return result.join(" ");
}

console.log(getDistance("2020-08-29 22:58:59", "2020-08-31 00:00:00"));
console.log(getDistance("2020-08-30 23:00:00", "2020-08-31 00:00:00"));
PS 연습장