Date관련된 기능들은 만들기 겁나 귀찮다.
그래서 그냥 ChatGPT에게 만들어 달라고 했다. 그랬더나 GPT가 함수 하나를 만들어 줬다.
원래 Date의 prototype에 해당 기능을 장착하려 했으나 prototype 사용을 권장하지 않고 상속으로 해결하라는 스택오버플로우의 답변을 듣고 Date를 상속받는 CustomDate클래스를 만들었다.
코드는 아래와 같다.
class CustomDate extends Date {
getTimeAgo = (): string => {
const now = new Date();
const years = now.getFullYear() - this.getFullYear();
const months = (now.getFullYear() - this.getFullYear()) * 12 + (now.getMonth() - this.getMonth());
const days = Math.floor((now.getTime() - this.getTime()) / (1000 * 60 * 60 * 24));
const hours = Math.floor((now.getTime() - this.getTime()) / (1000 * 60 * 60));
const minutes = Math.floor((now.getTime() - this.getTime()) / (1000 * 60));
if (years > 0) {
return `${years}년 전`;
}
if (months > 0) {
return `${months}개월 전`;
}
if (days > 0) {
return `${days}일 전`;
}
if (hours > 0) {
return `${hours}시간 전`;
}
if (minutes > 0) {
return `${minutes}분 전`;
}
return "방금 전";
}
}
export default CustomDate;
이렇게 쓰면 된다. Date랑 그냥 똑같이 사용하면 된다.
단지 getTimeAgo함수만 추가 됐을 뿐.
new CustomDate(forum.community.createdAt).getTimeAgo()
웹을 제대로 시작한지 얼마 되지 않았고 아직 볼 코드와 할 프로젝트와 일들이 산더미다. ㄱㄱㄱㄱㄱㄱ 가보자고