Home > Net >  Get 3 future day dates with php
Get 3 future day dates with php

Time:01-30

I want to creat a table for listing 3 future days with day name and date for my online shopping. I try this code but it doesn't work correctly :

        function week_from_monday($date) {
            // Assuming $date is in format DD-MM-YYYY
            list($day, $month, $year) = explode("-", $_REQUEST["date"]);

            // Get the weekday of the given date
            $wkday = date('l',mktime('0','0','0', $month, $day, $year));

            switch($wkday) {
                case 'Monday': $numDaysToMon = 0; break;
                case 'Tuesday': $numDaysToMon = 1; break;
                case 'Wednesday': $numDaysToMon = 2; break;
                case 'Thursday': $numDaysToMon = 3; break;
                case 'Friday': $numDaysToMon = 4; break;
                case 'Saturday': $numDaysToMon = 5; break;
                case 'Sunday': $numDaysToMon = 6; break;
            }

            // Timestamp of the monday for that week
            $monday = mktime('0','0','0', $month, $day-$numDaysToMon, $year);

            $seconds_in_a_day = 86400;

            // Get date for 7 days from Monday (inclusive)
            for($i=0; $i<7; $i  )
            {
                $dates[$i] = date('Y-m-d',$monday ($seconds_in_a_day*$i));
            }

            return $dates;
        }

        $ddate = date('Y-m-d');
        $date = new DateTime($ddate);
        $week = $date->format("W");

        $week_number = $week;
        $year = date('Y');
        for($day=5; $day<=30; $day  )
        {
            echo date('m/d/Y', strtotime($year."W".$week_number.$day))."\n";
        }

Here is my code but I want to get this :

today : Sun

Monday 30 Tuesday 31 Wednesday 1

CodePudding user response:

To get the next 3 upcoming dates, you can simplify this a lot using date and strotime.

Try this code:

function nextThreeDays($date) {
    $dateTs = strtotime($date);

    // Dont need this, but I leave it for educational purpose:
    // $day_of_week = date("N", $dateTs) - 1;    // Mon=0 Tue=1 Wed=2 ...
    // $monday_time = strtotime(date("d.m.Y H:i:s", $dateTs) . " -".$day_of_week." days");  // timestamp of monday of week of $date

    for($i = 1; $i <= 3; $i  ) {
        echo date('m/d/Y', strtotime(date("d.m.Y H:i:s", $dateTs) . "  ".$i." days"))."\n";
    }
}

// Put in "today : Sun"
nextThreeDays("29.01.2023");

Outputs:

// Monday 30 Tuesday 31 Wednesday 1
01/30/2023
01/31/2023
02/01/2023
  • Related