[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"));
profile
PS 연습장

0개의 댓글