Sunday, January 1, 2023

getting inclusive date range in php

As I assemble this year's Photos of the Year for my blog, I decided to make a tool to simplify a task I do a lot, which is taking the HTML for an image in one gallery and putting it into a new gallery. (Using the homebrew css-based photogallery I made a while back.)

Anyway, I had to look up how to get a range of dates in PHP (inclusive of the endpint, which needed an extra "modify"). So here's my code at the moment, which builds a form with two input fields (defaulting to last month), with sensible defaults for most things, and shows you the dates betwee 

<? 
    $now = date('Y-m-d');
    $end = requestval('end',$now);
    $before = date('Y-m-d',strtotime("-1 month"));
    $start = requestval('start',$before);
?>
<form>
    <label>start <input type="date" name="start" value="<? echo $start ?>"></label>
    <label>end <input type="date" name="end" value="<? echo $end ?>"></label>
    <button>go</button>
</form>
<ul>
<?
$periodstart = new DateTime($start);
$periodend = new DateTime($end);
$periodend->modify( '+1 day' ); 
$period = new DatePeriod($periodstart,new DateInterval('P1D'),$periodend);
foreach ($period as $key => $value) {
    $day = $value->format('Y-m-d')       ;
    echo "<li>$day";
}


function requestval($key, $default = ''){
    return isset($_REQUEST[$key]) ? $_REQUEST[$key] : $default;    
}
?>
</ul>

I like how PHP has such useful date stuff baked in, even if the API is kind of messy.

No comments:

Post a Comment