⛵ 항해99/TIL · WIL ✏️

[TIL] 2023.10.03 - 경과 시간 표시하기

hhhhy 2023. 10. 4. 08:02

 경과 시간 표시하기 

function formatTimeAgo(timestamp) {
  // 현재 시간을 가져옵니다.
  const now = new Date();
  
  // 입력된 timestamp를 Date 객체로 변환합니다.
  const createAt = new Date(timestamp);
  
  // 현재 시간과 입력된 시간의 차이를 계산합니다.
  const timeDiff = now - createAt;
  
  // 시간 차이를 시간 단위로 변환합니다.
  const hoursAgo = Math.floor(timeDiff / (1000 * 60 * 60));

  // 만약 1시간 이내라면...
  if (hoursAgo < 1) {
    // 시간 차이를 분 단위로 변환합니다.
    const minutesAgo = Math.floor(timeDiff / (1000 * 60));
    
    // 1분 미만이라면 "방금 전"을 반환합니다.
    if (minutesAgo < 1) {
      return "방금 전";
    }
    
    // 1분 이상이라면 "n분 전"을 반환합니다.
    return `${minutesAgo}분 전`;
  }

  // 1시간 이상 24시간 이내라면 "n시간 전"을 반환합니다.
  if (hoursAgo < 24) {
    return `${hoursAgo}시간 전`;
  }

  // 24시간 이상이라면...
  const daysAgo = Math.floor(hoursAgo / 24);
  
  // 하루 전인 경우 "어제"를 반환합니다.
  if (daysAgo === 1) {
    return "어제";
  }

  // 그 외의 경우, 년-월-일 시간:분 형식으로 날짜와 시간을 반환합니다.
  const formattedDate = `${createAt.getFullYear()}-${(createAt.getMonth() + 1).toString().padStart(2, "0")}-${createAt.getDate().toString().padStart(2, "0")} ${createAt.getHours().toString().padStart(2, "0")}:${createAt.getMinutes().toString().padStart(2, "0")}`;
  
  return formattedDate;
}