moment 라이브러리

Davina·2023년 1월 2일
0

All Empty Study 🫥

목록 보기
3/16

작성 글 업데이트 시간 표시하기

npm install moment --save

import moment from "moment";
function ElapsedTime(date) {
    const start = moment(date).add(9, "h"); //작성일자 => 들어오는 값에 9시간 더하기
    const end = moment(); //현재시간

    return end.to(start); //얼마 전 update되었는지

❗️ 백앤드 서버에서 들어오는 작성 시간이 현재 시간보다 9시간 전으로 들어와서 시간 차이가 계속 생겼음
ex) 방금 전 업데이트 된 글인데도 9 hours ago로 떴음

moment()를 이용해 .add(9, “h”)를 추가해줘서 9시간을 더하고 계산해줌으로써 해결

  • 일반 시간 알고리즘 구현
const diff = (end - start) / 1000; //현재시간-작성일자

    const times = [
        { name: "year", milliSeconds: 60 * 60 * 24 * 365 },
        { name: "months", milliSeconds: 60 * 60 * 24 * 30 },
        { name: "days", milliSeconds: 60 * 60 * 24 },
        { name: "hours", milliSeconds: 60 * 60 },
        { name: "mins", milliSeconds: 60 },
    ];

    for (const value of times) {
        const betweenTime = Math.floor(diff / value.milliSeconds);

        if (betweenTime > 0) {
            return `${betweenTime} ${value.name} ago`;
        }
    }
    return "Now";
profile
[많을 (다) 빛날 (빈)] 빛이나는 사람이 되고 싶습니다

0개의 댓글