javascript

timestamp javascirpt

jeeyong 2011. 3. 31. 11:09

트위터와 같은 Timestamp을 자바스크립으로 구현한 로직
/**
	timestamp(milliseconds);
**/
var timestamp = function (i) {
    var now = new Date();
    var currentDate = new Date(i);
    console.log(now.getTime()+" , "+currentDate.getTime());
    var diffMil = (now.getTime()) - (currentDate.getTime());
    console.log(diffMil);
    var diffSec = parseInt(diffMil/1000),
        diffMin = parseInt(diffSec / 60),
        diffHour = parseInt(diffMin / 60),
        diffDays = parseInt(diffHour / 24),
        diffMonth = parseInt(diffDays / 30),
        diffYear = parseInt(diffDays / 365);
    if (isNaN(diffMil) || diffMil < 0) {
        return ""
    }
    if(diffYear > 0) return diffYear+"년 전";
    else if(diffMonth > 0) return diffMonth+"개월 전";
    else if(diffDays > 0) return diffDays+"일 전";
    else if(diffHour > 0) return diffHour+"시간 전";
    else if(diffMin > 0) return diffMin+"분 전";
    else if(diffSec > 0) return diffSec+"초 전";
    else return "방금";
};