Javascript - 函数启用切换月份
function goLastMonth(month, year)
{
if (month == 1)
{
--year;
month = 13;
}
--month
var monthstring= ""+month+"";
var monthlength = monthstring.length;
if(monthlength <=1)
{
monthstring = "0" + monthstring;
}
document.location.href ="<?php $_SERVER['PHP_SELF'];?>?month="+monthstring+"&year="+year;
}
function goNextMonth(month, year)
{
if(month == 12)
{
++year;
month = 0;
}
++month
var monthstring= ""+month+"";
var monthlength = monthstring.length;
if(monthlength <=1)
{
monthstring = "0" + monthstring;
}
document.location.href ="<?php $_SERVER['PHP_SELF'];?>?month="+monthstring+"&year="+year;
}
</script>
PHP - 创建日历
if (isset($_GET['day']))
{
$day = $_GET['day'];
}
else
{
$day = date("j");
}
if(isset($_GET['month']))
{
$month = $_GET['month'];
}
else
{
$month = date("n");
}
if(isset($_GET['year']))
{
$year = $_GET['year'];
}
else
{
$year = date("Y");
}
$currentTimeStamp = strtotime( "$day-$month-$year");
$monthName = date("F", $currentTimeStamp);
$numDays = date("t", $currentTimeStamp);
$counter = 0;
?>
<table border='1'>
<tr>
<td><input style='width:50px;' type='button' value='<'name='previousbutton' onclick ="goLastMonth(<?php echo $month.",".$year?>)"></td>
<td colspan='5'><?php echo $monthName.", ".$year; ?></td>
<td><input style='width:50px;' type='button' value='>'name='nextbutton' onclick ="goNextMonth(<?php echo $month.",".$year?>)"></td>
</tr>
<tr>
<td width='50px'>Poniedziałek</td>
<td width='50px'>Wtorek</td>
<td width='50px'>Środa</td>
<td width='50px'>Czwartek</td>
<td width='50px'>Piątek</td>
<td width='50px'>Sobota</td>
<td width='50px'>Niedziela</td>
</tr>
<?php
echo "<tr>";
for($i = 1; $i < $numDays+1; $i++, $counter++)
{
$timeStamp = strtotime("$year-$month-$i");
if($i == 1)
{
$firstDay = date("w", $timeStamp);
for($j = 0; $j < $firstDay-1; $j++, $counter++)
{
echo "<td> </td>";
}
}
if($counter % 7 == 0)
{
echo"</tr><tr>";
}
$monthstring = $month;
$monthlength = strlen($monthstring);
$daystring = $i;
$daylength = strlen($daystring);
echo "<td align='center' ";
echo "><a href='".$_SERVER['PHP_SELF']."?month=".$monthstring."&day=".$daystring."&year=".$year."'>".$i."</a></td>";
}
echo "</tr>";
?>
</table>
日历运行良好,但当月中的第一天是星期日时,它开始计算星期一的日期(例如2016年5月)。我该如何解决这个问题?
答案 0 :(得分:0)
尝试以下代码
if($i == 1)
{
$firstDay = date("w", $timeStamp) - 1;
if ($firstDay < 0)
$firstDay = 6;
// Now monday is 0, and sunday is 6
for($j = 0; $j < $firstDay; $j++, $counter++) // remove the -1 in $firstDay-1
{
echo "<td> </td>";
}
}
日历的第一列是星期一,最后一列是星期日。 $firstDay = date("w", $timeStamp)
返回0-6之间的数字,其中0表示星期日,6表示星期六。所以我改变它,使0为星期一,6为星期日。
现在循环for($j = 0; $j < $firstDay; $j++, $counter++)
如果是星期一,那么因为它是第一列,所以你不希望循环运行。星期一,$firstDay
为0,因此循环不会运行。如果是星期二,则$firstDay
为1,循环运行一次,为星期一创建空白区域。