我有现在的剧本。var日期2需要自动获取当前日期,然后进行计算。我试了很多不走运的东西,请帮忙。

<script>

// Here are the two dates to compare
var date1 = '2015-09-08';
var date2 = '2015-12-13';

// First we split the values to arrays date1[0] is the year, [1] the month and [2] the day
date1 = date1.split('-');
date2 = date2.split('-');

// Now we convert the array to a Date object, which has several helpful methods
date1 = new Date(date1[0], date1[1], date1[2]);
date2 = new Date(date2[0], date2[1], date2[2]);

// We use the getTime() method and get the unixtime (in milliseconds, but we want seconds, therefore we divide it through 1000)
date1_unixtime = parseInt(date1.getTime() / 1000);
date2_unixtime = parseInt(date2.getTime() / 1000);

// This is the calculated difference in seconds
var timeDifference = date2_unixtime - date1_unixtime;

// in Hours
var timeDifferenceInHours = timeDifference / 60 / 60;

// in weeks :)
var timeDifferenceInWeeks = timeDifferenceInHours  / 24/7;

document.write(Math.ceil(timeDifferenceInWeeks));
</script>

最佳答案

您可以使用new Date()获取当前日期。请参考代码段。

<script>

// Here are the two dates to compare
var date1 = '2015-09-08';
var date2 = '2015-12-13';

// First we split the values to arrays date1[0] is the year, [1] the month and [2] the day
date1 = date1.split('-');
date2 = date2.split('-');

// Now we convert the array to a Date object, which has several helpful methods
date1 = new Date(date1[0], date1[1]-1, date1[2]);
date2 = new Date(date2[0], date2[1]-1, date2[2]);

// We use the getTime() method and get the unixtime (in milliseconds, but we want seconds, therefore we divide it through 1000)
date1_unixtime = parseInt(date1.getTime());
date2_unixtime = parseInt(date2.getTime());
date3_unixtime = parseInt((new Date()).getTime());

// This is the calculated difference in seconds
var timeDifference = date2_unixtime - date1_unixtime;

var timeDifferenceInWeeks1 = timeDifference / (1000*60*60*24*7);
var timeDifferenceInWeeks2 = (date3_unixtime - date2_unixtime) / (1000*60*60*24*7);

document.write(Math.ceil(timeDifferenceInWeeks1)+'--'+Math.ceil(timeDifferenceInWeeks2));
</script>

09-25 17:02
查看更多