10 PHP functions and code snippets to work with dates

on in Blog
Last modified on

Get current time, formatted

This is a super basic function, takes no parameters and returns the current date.

function now() {
    return date('d/m/Y', time());
}

Format a date

The easiest way to convert a date from a format (here yyyy-mm-dd) to another. For more extensive conversions, you should have a look at the DateTime class to parse & format.

$originalDate = '2020-01-21';
$newDate = date('d-m-Y', strtotime($originalDate));

Get week number from a date

When coding, you often find yourself in the need of getting the week number of a particular date. Pass your date as a parameter to this nifty function, and it will return you the week number.

function weeknumber($ddate) {
    $date = new DateTime($ddate);

    return $date->format('W');
}

Convert minutes to hours and minutes

Here is a super useful function for displaying times: give it minutes as an integer (let’s say 135) and the function will return 02:15. Handy!

function convertToHoursMins($time, $format = '%02d:%02d') {
    if ((int) $time < 1) {
        return;
    }
    $hours = floor($time / 60);
    $minutes = ($time % 60);

    return sprintf($format, $hours, $minutes);
}

Get difference between two times

This function takes two dates and returns the interval between those two. The result is set to be displayed in hours and minutes, you can easily change it on line 5 to fit your needs.

function dateDiff($date1, $date2) {
    $datetime1 = new DateTime($date1);
    $datetime2 = new DateTime($date2);
    $interval = $datetime1->diff($datetime2);

    return $interval->format('%H:%I');
}

Check if a date is in the past or in the future

Very simple conditional statements to check if a date is past, present, or future.

if (strtotime(dateString) > time()) {
    // Date is in the future
}

if (strtotime(dateString) < time()) {
    // Date is in the past
}

if(strtotime(dateString) == time()) {
    // Date is right now
}

Calculate age

This very handy function takes a date as a parameter, and returns the age. Very useful on websites where you need to check that a person is over a certain age to create an account.

function age($date) {
    $time = strtotime($date);
    if ($time === false) {
        return '';
    }

    $year_diff = '';
    $date = date('Y-m-d', $time);
    list($year, $month,$day) = explode('-', $date);
    $year_diff = date('Y') - $year;
    $month_diff = date('m') - $month;
    $day_diff = date('d') - $day;
    if ($day_diff < 0 || $month_diff < 0) {
        $year_diff-;
    }
 
    return $year_diff;
}

Show a list of days between two dates

An interesting example on how to display a list of dates between two dates, using DateTime() and DatePeriod() classes.

// Mandatory to set the default timezone to work with DateTime functions
date_default_timezone_set('Ireland/Dublin');

$start_date = new DateTime('2010-10-01');
$end_date = new DateTime('2010-10-05');

$period = new DatePeriod(
    $start_date, // start date
    new DateInterval('P1D'), // interval (1 day interval in this case)
    $end_date, // end date
    DatePeriod::EXCLUDE_START_DATE // (optional) self-explanatory
);

foreach ($period as $date) {
    echo $date->format('Y-m-d') . '<br/>'; // Display the dates in yyyy-mm-dd format
}

Twitter Style “Time Ago” Dates

Now a classic, this function turns a date into a nice “1 hour ago” or “2 days ago”, like many social media sites do.

function _ago($tm, $rcs = 0) {
    $cur_tm = time();
    $dif = $cur_tm-$tm;
    $pds = ['second', 'minute', 'hour', 'day', 'week', 'month', 'year', 'decade'];
    $lngh = [1, 60, 3600, 86400, 604800, 2630880, 31570560, 315705600];
    for ($v = sizeof($lngh) - 1; ($v >= 0) && (($no = $dif/$lngh[$v]) <= 1); $v--); if($v < 0) $v = 0; $_tm = $cur_tm - ($dif%$lngh[$v]);

    $no = floor($no);
    if ($no <> 1) {
        $pds[$v] .='s';
    }
    $x = sprintf("%d %s ", $no, $pds[$v]);
    if (($rcs == 1) && ($v >= 1) && (($cur_tm-$_tm) > 0)) {
        $x .= time_ago($_tm);
    }

    return $x;
}

Countdown to a date

A simple snippet that takes a date and tells how many days and hours are remaining until the aforementioned date.

$dt_end = new DateTime('December 3, 2016 2:00 PM');
$remain = $dt_end->diff(new DateTime());
echo $remain->d . ' days and ' . $remain->h . ' hours';

Difference in days between two dates #1

Given two dates. The task is to find the number of days between the given dates.

Examples:

Using date_diff() Function: The date_diff() function is an inbuilt function in PHP which is used to calculate the difference between two dates. This function returns a DateInterval object on the success and returns false on failure.

// PHP code to find the number of days between two given dates
// Creates DateTime objects
$datetime1 = date_create('17-09-2018');
$datetime2 = date_create('25-09-2018');

// Calculates the difference between DateTime objects
$interval = date_diff($datetime1, $datetime2);

// Display the result
// %R is + or - (for positive/negative)
echo $interval->format('%R%a days'); ?> 

Difference in days between two dates #2

$now = time(); // or your date as well
$your_date = strtotime("2010-01-31");
$datediff = $now - $your_date;

echo round($datediff / (60 * 60 * 24));

Difference in days between two dates #3

$earlier = new DateTime("2010-07-06");
$later = new DateTime("2010-07-09");

$diff = $later->diff($earlier)->format("%a");

Related posts