在PHP日历中获取一天的当前日期,月份和年份

时间:2019-03-18 15:19:33

标签: php calendar custom-data-attribute

我想编写一个PHP和JS日历,将单击的那一天写入数据库(并通过CSS类标记)。但是我遇到的问题之一是,我不知道哪个变量应该携带将要传递给JS的数据属性。

我的日历功能的代码如下:

<?php

function getCalender($date,$headline = array('Mo','Di','Mi','Do','Fr','Sa','So')) {
    // Days of the calendar month
    $sum_days = date('t',$date);
    // Days of the last month
    $LastMonthSum = date('t',mktime(0,0,0,(date('m',$date)-1),0,date('Y',$date)));

    foreach( $headline as $key => $value ) {
        echo "<div class='day headline'>".$value."</div>\n";
    }

    // If smaller then months ought to be in this month -> add a day
    for( $i = 1; $i <= $sum_days; $i++ ) {
        // Gets the day of the week (3 letters)
        $day_name = date('D',mktime(0,0,0,date('m',$date),$i,date('Y',$date)));
        // Gets the day of the week (numeric)
        $day_number = date('w',mktime(0,0,0,date('m',$date),$i,date('Y',$date)));

        // If it's the first of the month
        if( $i == 1) {
            // Defines 'todays' day of the week
            $s = array_search($day_name,array('Mon','Tue','Wed','Thu','Fri','Sat','Sun'));
            // If the 'today' is the first day of the month and no monday -> print the last days of last month until it's monday
            for( $b = $s; $b > 0; $b-- ) {
                $x = $LastMonthSum-$b;
                echo '<div class="day before" data-mydate="' . $i . '">'.sprintf("%02d",$x)."</div>\n";
            }
        } 

        // Checks if it's today -> adds style
        if( $i == date('d',$date) && date('m.Y',$date) == date('m.Y')) {
            echo '<div class="day current" data-mydate="' . $i . '">'.sprintf("%02d",$i)."</div>\n";
        } else {
            echo '<div class="day normal" data-mydate="' . $i . '">'.sprintf("%02d",$i)."</div>\n";
        }

        // Create new days until sunday, then start new week in new line
        if( $i == $sum_days) {
            $next_sum = (6 - array_search($day_name,array('Mon','Tue','Wed','Thu','Fri','Sat','Sun')));
            for( $c = 1; $c <=$next_sum; $c++) {
                echo "<div class='day after'> ".sprintf("%02d",$c)." </div>\n"; 
            }
        }
    }
}
?>

然后用于创建日历:

<!-- Wrapper for Calendar CSS and toggle-function for days -->
<div class="calender" id="chocToggle">
    <div class="pagination">
    <div class="pagihead">
        <span><?php echo $arrMonth[date('F',$date)];?> <?php echo date('Y',$date); ?></span>
    </div>
    </div>
<!-- Creates the calendar -->
<?php getCalender($date,$headline); ?>
    <!-- Makes sure there's no floating elements on the left side -->
    <div class="clear"></div>
</div>

目前,我已将$ i设置为data-mydate。仅显示给我该月的天数。有人可以帮忙吗?

0 个答案:

没有答案