2013-02-23 106 views
0

我已經編寫了一個代碼來計算網站上的內容的年齡。這是效率低下,計算結果不大。我以前寫過這個腳本,上次它工作的很完美,但我找不到它該死的文件。有沒有更好的方法來計算內容的年齡

我認爲計算問題是由年份引起的。任何人都可以爲我提出修補嗎?創建日期格式爲YYYYMMDD,輸出整週(這很重要),即下面的示例應輸出'52'周。

var created='20120223'; 
var year=Number(created.substr(0,4)); 
var month=Number(created.substr(4,2))-1; 
var day=Number(created.substr(6,2)); 
var d = new Date(); 
var curr_date = d.getDate(); 
var curr_month = d.getMonth() + 1; 
var curr_year = d.getFullYear(); 
var input_age = ((((curr_year - year)*31536000) + ((curr_month - month)*2678400) + ((curr_date - day)*86400))/604800).toFixed(0); 
document.getElementById('item12345_input').value = input_age + ' weeks'; 

回答

2

您正在先減去一個月。那麼你又增加了一個月。試試這個

var created='20120223'; 
var year=Number(created.substr(0,4)); 
var month=Number(created.substr(4,2))-1; 
var day=Number(created.substr(6,2)); 
var d = new Date(); 
var curr_date = d.getDate(); 
var curr_month = d.getMonth(); 
var curr_year = d.getFullYear(); 
var input_age = ((((curr_year - year)*31536000) + ((curr_month - month)*2678400) + ((curr_date - day)*86400))/604800).toFixed(0); 
alert(input_age + ' weeks'); 
+0

這很好,感謝polin,我非常感謝。 – 2013-02-23 06:01:41

+0

謝謝。樂於幫助 – polin 2013-02-23 06:06:29

0

只需要減去2日期。

var createdDate = new Date(
    +created.substring(0, 4), // Four digit year 
    created.substring(4, 6)-1, // Base-zero month 
    +created.substring(6, 8)); // Day of month 
var ageMillis = (new Date) - createdDate; 
var MS_PER_WEEK = 1000/* ms /sec */ 
       * 60 /* sec/min */ 
       * 60 /* min/hr */ 
       * 24 /* hr /day */ 
       * 7 /* day/wk */; 
var ageWeeks = ageMillis/MS_PER_WEEK; 
+1

咳咳 - 個是基於0。 – mplungjan 2013-02-23 05:54:19

+0

感謝邁克,這看起來高效而精確。有一個問題,您是否可以稍微修改以包含創建日期的值(即20120130)? – 2013-02-23 05:57:08

+0

@mplungjan,好點。固定。 – 2013-02-23 07:34:17

0

注月份是0基於

<script> 
var created ="20120223"; 
var yyyy = +created.substring(0, 4); 
var mm = created.substring(4, 6)-1; 
var dd = +created.substring(6, 8); 
var createdDate = new Date(yyyy,mm,dd); 
var ageMillis = new Date().getTime() - createdDate.getTime(); 
var MS_PER_WEEK = 1000/* ms /sec */ 
       * 60 /* sec/min */ 
       * 60 /* min/hr */ 
       * 24 /* hr /day */ 
       * 7 /* day/wk */; 
var ageWeeks = parseInt(ageMillis/MS_PER_WEEK); 

alert("Created on " +mm+"/"+dd+"/"+yyyy+" which is "+ageWeeks+ " week"+(ageWeeks==1?"":"s")+" ago"); 

</script> 
0

你可以試試這個:

var created='20120223'; 
    var year=Number(created.substr(0,4)); 
    var month = Number(created.substr(4,2)); 
    if (Number(created.substr(4,2)) < 10){ 
     month = '0'+ Number(created.substr(4,2)); 
    } 
    var day=Number(created.substr(6,2)); 
    var dt = year+'-'+month+'-'+day; 
    var dif = new Date().getTime() - Date.parse(dt); 
    var divWeek = 7 * 24 * 60 * 60 * 1000; 
    alert(Math.round(dif/divWeek));