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';
4

4 回答 4

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');
于 2013-02-23T05:47:45.450 回答
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;
于 2013-02-23T05:41:50.557 回答
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>
于 2013-02-23T06:01:45.407 回答
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));
于 2013-02-23T06:11:31.650 回答