Sling Academy
Home/PHP/PHP: Convert date time to time ago and vice versa

PHP: Convert date time to time ago and vice versa

Last updated: January 09, 2024

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.

Next Article: PHP: Get an array of dates between two dates

Previous Article: PHP: Convert timestamp to date time and vice versa

Series: Basic PHP Tutorials

PHP

You May Also Like

  • Pandas DataFrame.value_counts() method: Explained with examples
  • Constructor Property Promotion in PHP: Tutorial & Examples
  • Understanding mixed types in PHP (5 examples)
  • Union Types in PHP: A practical guide (5 examples)
  • PHP: How to implement type checking in a function (PHP 8+)
  • Symfony + Doctrine: Implementing cursor-based pagination
  • Laravel + Eloquent: How to Group Data by Multiple Columns
  • PHP: How to convert CSV data to HTML tables
  • Using ‘never’ return type in PHP (PHP 8.1+)
  • Nullable (Optional) Types in PHP: A practical guide (5 examples)
  • Explore Attributes (Annotations) in Modern PHP (5 examples)
  • An introduction to WeakMap in PHP (6 examples)
  • Type Declarations for Class Properties in PHP (5 examples)
  • Static Return Type in PHP: Explained with examples
  • PHP: Using DocBlock comments to annotate variables
  • PHP: How to ping a server/website and get the response time
  • PHP: 3 Ways to Get City/Country from IP Address
  • PHP: How to find the mode(s) of an array (4 examples)
  • PHP: Calculate standard deviation & variance of an array