Untitled

 avatar
unknown
plain_text
5 days ago
1.4 kB
4
Indexable
function getDateRange($option, DateTime $today = null) {
    $today = $today ?? new DateTime(); // today (excluded)
    $end = clone $today;
    $end->modify('-1 day'); // set end to yesterday
    $start = clone $end;

    switch (strtolower($option)) {
        case 'yesterday':
            // start and end already set to yesterday
            break;

        case 'last7d':
            $start->modify('-6 days'); // excludes today, range: 7 days ending yesterday
            break;

        case 'last14d':
            $start->modify('-13 days'); // 14 days ending yesterday
            break;

        case 'this_month':
            $start->modify('first day of this month');
            $end = new DateTime(); // today
            $end->modify('-1 day'); // yesterday
            break;

        case 'last30d':
            $start->modify('-29 days'); // 30 days ending yesterday
            break;

        case 'last_month':
            $start->modify('first day of last month');
            $end->modify('last day of last month');
            break;

        default:
            throw new Exception("Unsupported date range option: $option");
    }

    return [
        'start' => $start->format('Y-m-d'),
        'end' => $end->format('Y-m-d')
    ];
}



$today = new DateTime('2025-04-03');
$range = getDateRange('last7d', $today);
echo "From {$range['start']} to {$range['end']}";
Editor is loading...
Leave a Comment