April 29, 2025 - 22:59
PHP Code Examples - Part 2 Image
PHP

PHP Code Examples - Part 2

Comments

I continue to share some handy utility functions that are good to always have within reach. This time, my focus is on date-related functions.

The first function calculates the difference between two dates and returns the result in years, months, and days. It's quite short and simple.

PHP
function work_duration($date1, $date2) {
    $d1 = date_create($date1);
    $d2 = date_create($date2);
    $diff = date_diff($d1, $d2)->format('%y years, %m months, %d days');
    return $diff;
}

To run it:

PHP
echo work_duration('2020-04-01','2020-05-20');

Next function: this one returns the first and last day of the current week.

PHP
function week_dates() {
    $start = new DateTime('last sunday');
    $start->modify('+1 day');
    $end = clone ($start);
    $end->modify('+6 days');
    $first_day = $start->format('d.m.Y');
    $last_day = $end->format('d.m.Y');
    $dates = array(
        0 => $first_day,
        1 => $last_day
    );
    return $dates;
}

First assign the result to a variable:

PHP
$week_dates = week_dates();

To get the first date:

PHP
echo $week_dates[0];

And to get the last date:

PHP
echo $week_dates[1];

The function below returns the first and last day of the previous month:

PHP
function month_dates() {
    $start = new DateTime('first day of last month');
    $end = new DateTime('last day of last month');
    $first = $start->format('d.m.Y');
    $last = $end->format('d.m.Y');
    $dates = array(
        0 => $first,
        1 => $last
    );
    return $dates;
}

To call the function:

PHP

$month_dates = month_dates();
echo $month_dates[0]; // First day
echo $month_dates[1]; // Last day

And now, let’s add a function to calculate age:

PHP
function age($birthdate) {
    $today = date('Y-m-d');
    $d1 = date_create($today);
    $d2 = date_create($birthdate);
    $age = date_diff($d1, $d2)->format('%y');
    return $age;
}

To use it simply:

PHP
echo age('1970-01-01');

This will return only the difference in years.

Related Articles

Comments ()

No comments yet. Be the first to comment!

Leave a Comment