PHP: Convert date time to time ago and vice versa

Updated: January 9, 2024 By: Guest Contributor Post a comment

Introduction

Handling dates and times is a common requirement in many PHP applications. Whether you’re developing a social network, a blogging platform, or a personal project, displaying the relative time, such as ‘2 minutes ago’ or converting such phrases back into a standardized date-time, is useful for improving user experience. This tutorial guides you through various PHP functions and approaches to achieve these conversions effortlessly.

Convert Date Time to Time Ago

Converting a specific date and time to a ‘time ago’ format, such as ‘seconds ago’, ‘minutes ago’, etc., gives users a sense of how recent an event occurred. The following example shows how to create a simple PHP function to perform this conversion:

function timeAgo($datetime) {
    $time = strtotime($datetime);
    $diff = time() - $time;

    if ($diff < 60) {
        return 'Just now';
    }

    $timeRules = [
        ['minute', 60],
        ['hour', 3600],
        ['day', 86400],
        ['week', 604800],
        ['month', 2592000],
        ['year', 31536000],
    ];

    foreach ($timeRules as $rule) {
        $divided = $diff / $rule[1];
        if ($divided >= 1) {
            $r = round($divided);
            return $r . ' ' . ($r > 1 ? $rule[0].'s' : $rule[0]) . ' ago';
        }
    }
}

This function takes a date-time string as input, calculates the difference between the current time and the provided time, and then displays a readable ‘time ago’ format.

Converting ‘Time Ago’ to Date Time

While showing ‘time ago’ is helpful, there are situations where you need to convert it back into a standard date and time format. The following example demonstrates this conversion:

function timeAgoToDate($timeAgo) {
    $currentTime = time();
    $timeAgo = strtolower($timeAgo);

    $deconstructed = sscanf($timeAgo, '%d %s ago', $value, $unit);
    if($deconstructed < 2) {
        // Handle error
        return null;
    }

    $unitsToSeconds = [
        'second' => 1,
        'minute' => 60,
        'hour'   => 3600,
        'day'    => 86400,
        'week'   => 604800,
        'month'  => 2592000,
        'year'   => 31536000,
    ];

    if (isset($unitsToSeconds[$unit]) || isset($unitsToSeconds[$unit.'s'])) {
        $unit = rtrim($unit, 's');
        $secondsAgo = $value * $unitsToSeconds[$unit];
        $date = date('Y-m-d H:i:s', $currentTime - $secondsAgo);
        return $date;
    }    

    return null;
}

In this function, we take a string like ‘3 days ago’, extract the numeric value and time unit, and subtract the corresponding number of seconds from the current time to get the original date and time.

Utilizing DateTime Class

PHP’s DateTime class provides an object-oriented way to manipulate date and time. Below is an example of how to use DateTime to convert date time to time ago and time ago to DateTime:

// DateTime to Time Ago
function dateTimeToTimeAgo(Datetime $datetime) {
    // Code similar to the above timeAgo function
}

// Time Ago to DateTime
function timeAgoToDateTime($timeAgo) {
    // Code similar to the above timeAgoToDate function
}

Using the DateTime class allows for more flexibility, time zone support, and better error handling through the built-in methods.

Handling Localization and Time Zones

Dealing with users from different locales requires considering localization and time zones when converting time. We can use DateTimeZone and IntlDateFormatter to handle these concerns:

// Convert to localized time ago
function localizedTimeAgo(DateTime $datetime, $locale) {
    // Localization example
}

// Convert localized time ago back to DateTime
function localizedTimeAgoToDateTime($timeAgo, $timezone) {
    // Conversion example, with time zone support
}

This advanced section shows how to tailor our earlier functions for internationalization, accounting for various languages and time zones.

Conclusion

Time-related conversions are integral to creating friendly user experiences in PHP applications. We’ve explored basic to advanced techniques for converting dates and times to a ‘time ago’ format and vice versa. By understanding PHP’s date and time functions, along with implementing modern object-oriented concepts like the DateTime and DateTimeZone classes, you can effortlessly handle time manipulation in your projects.