繁体   English   中英

PHP日历跳过2月

[英]PHP calendar skips February

我已经看过,但是没有找到答案。

我有一个php日历,当去下个月或上个月从1月到2月时,它跳过2月,反之亦然,从3月到2月,它跳过了2月。 它每4年执行一次此操作,因此我知道它与leap年有关,但似乎找不到问题。

这是代码:

<html>
<head>
<script>
function goLastMonth(month, year){
if (month == 1) {
--year;
month = 13;
}
document.location.href = "<?php $_SERVER['PHP_SELF'];?>?month="+(month-1)+"&year="+year;
}

function goNextMonth(month, year){
if (month == 12) {
++year;
month = 0;
}
document.location.href = "<?php $_SERVER['PHP_SELF'];?>?month="+(month+1)+"&year="+year;
}



</script> 




</head>

<body>
<?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"); 
}

// calender variable // 
$currentTimeStamp = strtotime("$year-$month-$day");
$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' align='center'> <?php echo $monthName.", ".$year; ?></td>
<td><input style='width:50px;' type='button' value='>' name='nextbutton' onclick="goNextMonth(<?php echo $month.",".$year?>)"></td>
<td></td> 
</tr>
<tr>
<td width='50px' align='center'>D</td>
<td width='50px' align='center'>L</td>
<td width='50px' align='center'>M</td>
<td width='50px' align='center'>M</td>
<td width='50px' align='center'>J</td>
<td width='50px' align='center'>V</td>
<td width='50px' align='center'>S</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; $j++, $counter++) {
// blank space //
echo "<td>&nbsp;</td>";
} 
}
if ($counter % 7 == 0 && $counter != 0){
echo "</tr><tr>";
}
echo "<td align='center'>".$i."</td>";
}
echo "</tr>";
?>

</table>

</body>

我怀疑您的问题是Javascript将1月视为第0个月,而PHP将1月视为第1个月。

我觉得您已经翻转了。

您是从JavaScript还是PHP获得收益? 如果使用JavaScript,则永远不应该有第12个月。无论哪种情况,都绝对不要有第13个月。

由于您说的是month而不是$month我将假设它来自Javascript。 在这种情况下,我想我会这样更改:

function goLastMonth(month, year){
    if (month == 0) {
        --year;
        month = 11;
}

...

function goNextMonth(month, year){
    if (month == 11) {
        ++year;
        month = 0;
}

...

if (isset($_GET['day'])) {
    $day = $_GET['day'];
} else { 
    $day = date("j");
}

...

$currentTimeStamp = strtotime("$year-$month-$day");

如果没有给出明确的日期,则说明您正在使用当前日期。 猜猜是什么,今天是30号。 没有2月30日。 然后,您将以此为基础进行所有日期计算。

如果要为某个月制作时间戳记,然后迭代到下个月,请始终以该月初为准。 1月1日+ 1个月有意义,1月30日+ 1个月没有意义。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM