Skip to content

Instantly share code, notes, and snippets.

@code-boxx
Created May 28, 2023 11:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save code-boxx/140087b519ce113058f22db72a7db929 to your computer and use it in GitHub Desktop.
Save code-boxx/140087b519ce113058f22db72a7db929 to your computer and use it in GitHub Desktop.
PHP Date Range

PHP DATE RANGE

https://code-boxx.com/date-range-php/

LICENSE

Copyright by Code Boxx

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

<?php
// (A) START & END DATE
$start = new DateTime("2020-01-01");
$end = new DateTime("2020-03-02");
// (B) DAILY INTERVAL
// USE P2D FOR 2 DAYS, P3D FOR 3 DAYS, AND SO ON...
echo "DAILY<br>";
$interval = new DateInterval("P1D");
$range = new DatePeriod($start, $interval, $end);
foreach ($range as $date) {
echo $date->format("Y-m-d") . "<br>";
}
// (C) WEEKLY INTERVAL - CAPTAIN OBVIOUS P7D
echo "WEEKLY<br>";
$interval = new DateInterval("P7D");
$range = new DatePeriod($start, $interval, $end);
foreach ($range as $date) {
echo $date->format("Y-m-d") . "<br>";
}
// (D) MONTHLY INTERVAL
echo "MONTHLY<br>";
$interval = new DateInterval("P1M");
$range = new DatePeriod($start, $interval, $end);
foreach ($range as $date) {
echo $date->format("Y-m-d") . "<br>";
}
<?php
// (A) START & END UNIX TIMESTAMPS
$start = strtotime("2020-01-01");
$end = strtotime("2020-03-02");
// (B) DAILY INTERVAL (1 DAY = 86400 SECONDS)
echo "DAILY<br>";
for ($i=$start; $i<=$end; $i+=86400) {
echo date("Y-m-d", $i) . "<br>";
}
// (C) WEEKLY INTERVAL (1 DAY = 604800 SECONDS)
echo "WEEKLY<br>";
for ($i=$start; $i<=$end; $i+=604800) {
echo date("Y-m-d", $i) . "<br>";
}
// (D) MONTHLY INTERVAL
echo "MONTHLY<br>";
$i = $start;
while ($i < $end) {
$idate = date("Y-m-d", $i);
echo $idate."<br>";
$i = strtotime($idate . "+1 month");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment