2015-09-17 54 views
-1

我試圖使用下面的JavaScript動態更新的時間戳1 minute agoX分鐘前的JavaScript功能不能正常工作

setInterval('relativeTime()', 1000); 

function relativeTime() 
{ 
    console.log(timeSince('2015-09-17 14:59:10')); 
} 


function timeSince(date) { 
    if (typeof date !== 'object') { 
     date = new Date(date); 
    } 

    var seconds = Math.floor((new Date() - date)/1000); 
    var intervalType; 

    var interval = Math.floor(seconds/31536000); 
    if (interval >= 1) { 
     intervalType = 'year'; 
    } else { 
     interval = Math.floor(seconds/2592000); 
     if (interval >= 1) { 
      intervalType = 'month'; 
     } else { 
      interval = Math.floor(seconds/86400); 
      if (interval >= 1) { 
       intervalType = 'day'; 
      } else { 
       interval = Math.floor(seconds/3600); 
       if (interval >= 1) { 
        intervalType = "hour"; 
       } else { 
        interval = Math.floor(seconds/60); 
        if (interval >= 1) { 
         intervalType = "minute"; 
        } else { 
         interval = seconds; 
         intervalType = "second"; 
        } 
       } 
      } 
     } 
    } 

    if (interval > 1 || interval === 0) { 
     intervalType += 's'; 
    } 

    return interval + ' ' + intervalType; 
}; 

的jsfiddle:http://jsfiddle.net/5qpxrta9/2/

的錯誤我得到:

Uncaught ReferenceError: relativeTime is not defined

+0

我可以問你爲什麼不使用moment.js? – dcohenb

+1

你說這不起作用..你是什麼意思?有錯誤嗎? –

+0

在瀏覽器中使用開發人員工具。 'Uncaught SyntaxError:missing)'參數列表後' – Quentin

回答

1

你沒有在小提琴上定義jQuery,你的函數用法在函數聲明之前,而你的Date聲明使用了錯誤的格式。

function relativeTime() { 
    $('#time').text(timeSince('2015-09-17T14:59:10')); 
} 

setInterval(relativeTime, 1000); 
+0

非常感謝!這確實起作用。 – user1012181