Skip to content
PHP Logo

How can PHP be used to efficiently trim dates within a specific time range?

To efficiently trim dates within a specific time range in PHP, you can use the DateTime class along with the DateTime::diff method to compare dates and filter out those that fall within the specified range.

php
// Define the start and end dates of the time range
$start_date = new DateTime('2022-01-01');
$end_date = new DateTime('2022-12-31');

// Loop through an array of dates and filter out those within the time range
$dates = ['2022-03-15', '2022-06-30', '2022-10-20', '2023-02-05'];
$filtered_dates = array_filter($dates, function($date) use ($start_date, $end_date) {
    $current_date = new DateTime($date);
    $diff_start = $current_date->diff($start_date)->format("%r%a");
    $diff_end = $current_date->diff($end_date)->format("%r%a");
    
    return $diff_start >= 0 && $diff_end <= 0;
});

print_r($filtered_dates);