WEB/JS

[javascript] 자바스크립트로 방금/몇초전/몇분전/몇시간전/몇달전/몇년전 출력하기

나나나나나나나ㅏ나난ㄴ나ㅏ나나 2023. 5. 17. 13:39
728x90
  const today = new Date();
    const timeValue = new Date(date);


    const betweenTime = Math.floor((today.getTime() - timeValue.getTime()) / 1000 / 60);
    if (betweenTime < 1) return '방금전';
    if (betweenTime < 60) {
        return `${betweenTime}분전`;
    }

    const betweenTimeHour = Math.floor(betweenTime / 60);
    if (betweenTimeHour < 24) {
        return `${betweenTimeHour}시간전`;
    }

    const betweenTimeDay = Math.floor(betweenTime / 60 / 24);
    if (betweenTimeDay < 365) {
        return `${betweenTimeDay}일전`;
    }

    return `${Math.floor(betweenTimeDay / 365)}년전`;
728x90