Calendar in PHP

Asked

Viewed 4,711 times

1

I have a calendar in php and would like to know two things !

How to make the date start Monday ? (Monday 1, for example) and how to make Sundays appear in red.

Here’s the code:

<!DOCTYPE HTML>
<html lang="pt-br">
<head>
    <meta charset="UTF-8">
    <title>Calendário em PHP</title>
    <?php 
        date_default_timezone_set('America/Sao_Paulo');
    ?>
</head>
<body>
    <h1>Estamos em <?php echo date('Y');?></h1>
        <p>Hoje é dia <strong><?php echo date('d / '); ?></strong>
            <?php echo date('m'); ?>
            agora são <?php echo date ('H'); ?>horas e
            <?php echo date('i');?> minutos.</p>

        <?php
            function linha($semana){
                echo "<tr>";
                for ($i = 0; $i <=6; $i++){
                    if(isset($semana[$i])){
                        echo "<td>{$semana[$i]}</td>";
                    } else{
                        echo "<td></td>";
                    }
                }
                echo "</tr>";
            }
            function calendario(){
                $dia = 1;
                $semana = array();

                while($dia <= 31){
                    array_push($semana, $dia);
                    if(count($semana) == 7){
                        linha($semana);
                        $semana = array();
                    }
                    $dia++;
                }
                linha($semana);
            }
        ?>
        <table border="1">
            <tr>
                <th>Dom</th>
                <th>Seg</th>
                <th>Ter</th>
                <th>Qua</th>
                <th>Qui</th>
                <th>Sex</th>
                <th>Sáb</th>
                <?php calendario(); ?>
            </tr>
        </table>
</body>
</html>
  • For parts, to paint Sundays red is simple, in its line function vc creates an if by checking if the number is the corresponding Sunday, if it is vc puts a tag class in its tr(ex: <tr class="red"> and stylizes with CSS(ex: . red{ color: red;}). Already to count from second there are several ways, we know that the date() command can return numbers that represent the days of the week (Sunday = 1, Monday =2 and etc), just that in its array of days you use the for from 1 to n-1 and put the index 0 last, after the execution of the is, which in this case represents Sunday.

2 answers

3

Try:

<!DOCTYPE HTML>
<html lang="pt-br">
<head>
    <meta charset="UTF-8">
    <title>Calendário em PHP</title>
    <?php 
        date_default_timezone_set('America/Sao_Paulo');

        $hoje = getdate(strtotime($_GET['t']));

        $ultimoDia = cal_days_in_month(CAL_GREGORIAN,
                                       $hoje['mon'],
                                       $hoje['year']);

        $primeiraSemana = (($hoje['wday'] + 1) -
                          ($hoje['mday'] - ((int)($hoje['mday'] / 6) * 7))) % 7;
        // Alternativa:
        /*$primeiroDiaTimestamp = strtotime(sprintf("%d-%0d-01",
                                                  $hoje['year'],
                                                  $hoje['mon']));
        $primeiraSemana = (int)date('w', $primeiroDiaTimestamp);*/
    ?>

    <style>
        td[data-semana="0"] { color: #ff0000; }
    </style>
</head>
<body>
    <h1>Estamos em <?= $hoje['year'] ?></h1>
    <p><?= sprintf('Hoje é dia <strong>%0d / %0d</strong>, agora são %02d horas e %0d minutos.',
                   $hoje['mday'], $hoje['mon'], $hoje['hours'], $hoje['minutes'])
    ?></p>

    <table border="1">
        <tr>
            <th>Dom</th>
            <th>Seg</th>
            <th>Ter</th>
            <th>Qua</th>
            <th>Qui</th>
            <th>Sex</th>
            <th>Sáb</th>
        </tr>
        <tr>
        <?php
        for($semana = 0; $semana < $primeiraSemana; ++$semana) {
            echo '<td>&nbsp;</td>';
        }
        for($dia = 1; $dia < $ultimoDia; ++$dia) {
            if( $semana > 6 ) {
                $semana = 0;
                echo '</tr><tr>';
            }

            echo "<td data-semana=\"$semana\">";
            echo "$dia</td>";
            ++$semana;
        }
        for(; $semana < 7; ++$semana) {
            echo '<td>&nbsp;</td>';
        }
        ?>
        </tr>
    </table>
</body>
</html>

I put the CSS style in HTML, but it’s good practice to put it in another CSS-only file.

I used the function cal_days_in_month to have the last day of the month.

To find out what day of the week was, I showed you two solutions:

  • using the function strtotime to obtain the "timestamp" of the first day of the month, which can then be used in the function date
  • making an arithmetic calculation (I suppose "performance" is better - it does not invoke two complex functions):

    1. account of the full week of the month that has passed to this day: (int)($hoje['mday'] / 6;
    2. subtracts today by the days of the full weeks counted, giving the days that are left: $hoje['mday'] - ((int)($hoje['mday'] / 6) * 7)
    3. subtracts the number of the day of the week plus one (Sunday is 0, Monday is 1, ...) by the previous result: ($hoje['wday'] + 1) - ($hoje['mday'] - ((int)($hoje['mday'] / 6) * 7))

    For example, today is the 11th and Saturday. It has only been a full week (11 / 6 = 1.6...). A week has 7 days (1 * 7 = 7). They passed 4 days after 7 days (11 - 7 = 4). If the first day of the week were Sunday, after a week plus four days it would be Wednesday. It is necessary to pull the days to Saturday (7 days): 7 - 4 = 3 (a Wednesday).

The rest is easy:

  1. lets pass days that are not shown in the calendar.
  2. shows the days of the month indicating the day of the week in the "td" element; when it is Saturday, the line ends (I assume you are using HTML5, which allows attributes data-*).
  3. Finally, let the remaining days pass until the end of the week (Saturday).
  • Now just don’t make a calendar in PHP that you don’t want :) +1+

  • Note that I corrected an error in the calculations after tests.

  • @Pedroamaralcouto. I tested your code, but in the month of 10/2018, it puts 30 days and not 31. I noticed that has this line $hoje = getdate(strtotime($_GET['t']));. The variable $_GET['t'], where does it come from? Thank you!

1

function linha($semana){
    $dias = count($semana);
    echo "<tr>";
    for ($i = 1; $i < $dias; $i++){
        if(isset($semana[$i])){
            echo "<td>{$semana[$i]}</td>";
        } else{
            echo "<td></td>";
        }
    }
    echo "<td class="vermelho">{$semana[0]}</td>";
    echo "</tr>";   }

To complement my previous comment, it would be something like this. I did not test the code because it is simple to implement, if there is something wrong you give an adjusted, which is very simple.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.