我编写了一个代码来计算网站上的内容年龄。它效率低下,而且计算方法也很偏僻。我以前写过这个剧本,上次它完美地工作了,但是我找不到它该死的文件。
我认为计算问题是由年引起的。任何人都可以建议我修复?创建日期格式为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';
答案 0 :(得分: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');
答案 1 :(得分: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;
答案 2 :(得分: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>
答案 3 :(得分: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));