如何在html脚本中插入当前日期

时间:2015-12-14 04:19:38

标签: javascript html

我有当前的脚本。 var date 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>

3 个答案:

答案 0 :(得分:1)

您可以使用new Date()获取当前日期。请参阅片段。

&#13;
&#13;
<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>
&#13;
&#13;
&#13;

答案 1 :(得分:1)

只需使用

var date2 = new Date();

现在,date2保存了您机器的当前日期和时间。

答案 2 :(得分:0)

我改为php代码,以下是我的工作。

<?
$strtDate = '2015-09-08';
$endDate = date('Y-m-d');

//$endDate = 'new Date();';
$startDateWeekCnt = round(floor( date('d',strtotime($strtDate)) / 7)) ;

// echo $startDateWeekCnt ."\n";
$endDateWeekCnt = round(ceil( date('d',strtotime($endDate)) / 7)) ;

//echo $endDateWeekCnt. "\n";
$datediff = strtotime(date('Y-m',strtotime($endDate))."-01") - strtotime(date('Y-m',strtotime($strtDate))."-01");
$totalnoOfWeek = round(floor($datediff/(60*60*24)) / 7) + $endDateWeekCnt - $startDateWeekCnt ;
echo $totalnoOfWeek ."\n";
?>