길/Javascript 기본

작성 시간과 현재 시간을 이용하여 ~전 출력

7he8oy 2021. 2. 7. 19:11
function returnTimeBefore(tweet){
    let endtime = Date.now();
    let starttime = tweet.created_at;
    let timebefore = endtime-starttime;


    //timebefore는 miliseconds 단위의 시간 차다.
    //이것을 연,월,일,시간,분 단위로 쪼개는 것을 하면 됨.
    let toseconds = timebefore/1000
    let appendtotimebefore = ''
    
    let oneyear = 3.154e+7;
    let onemonth = 2.628e+6;
    let oneweek = 604800;
    let oneday = 86400;
    let onehour = 3600;
    let onemin = 60;
    
    if(toseconds>oneyear){
        appendtotimebefore = `${Math.floor(toseconds/oneyear)}년 전`
    } else if (toseconds>onemonth){
        appendtotimebefore = `${Math.floor(toseconds/onemonth)}달 전`
    } else if (toseconds>oneweek){
        appendtotimebefore = `${Math.floor(toseconds/oneweek)}주 전`
    } else if (toseconds>oneday){
        appendtotimebefore = `${Math.floor(toseconds/oneday)}일 전`
    } else if (toseconds>onehour){
        appendtotimebefore = `${Math.floor(toseconds/onehour)}시간  전`
    } else if (toseconds>onemin){
        appendtotimebefore = `${Math.floor(toseconds/onemin)}분 전`
    } else {
        appendtotimebefore = '방금 전'
    }

    return tweet.timebefore = appendtotimebefore
}​

Date.now()는 현재 시간을 리턴한다.

이때 리턴되는 시간은 milliseconds 단위로 리턴된다.

따라서 Date.now()와 작성 시간을 뺀 후,

이를 각 시간 단위에 해당하는 milliseconds로 나눈 것을 출력하면 된다.

 

' > Javascript 기본' 카테고리의 다른 글

타이머 API  (0) 2021.02.09
동기와 비동기  (0) 2021.02.09
Mapreduce  (0) 2021.02.03
정규표현식  (0) 2021.02.02
정규표현식  (0) 2021.02.02