JSP/Muzi
[Javascript]등록일자 경과 시간으로 나타내기 함수
미눅스[멘토]
2023. 10. 4. 14:32
728x90
몇초 전
몇분 전
몇시간 전
몇일 전
으로 출력하고 싶을 떄가 있다.
아래 코드를 참고하자
// 등록일자 시간 나타내기
function convertTimeToRelative(timeInMilliseconds) {
const currentTime = new Date().getTime();
const timeDifference = currentTime - timeInMilliseconds;
const seconds = Math.floor(timeDifference / 1000);
const minutes = Math.floor(seconds / 60);
const hours = Math.floor(minutes / 60);
const days = Math.floor(hours / 24);
if (days > 0) {
return days + "일 전";
} else if (hours > 0) {
return hours + "시간 전";
} else if (minutes > 0) {
return minutes + "분 전";
} else {
return "방금 전";
}
}