#45 - Time Format PHP Class

Date: 2019-01-26 12:00 - PHP

PHP Class to format time in an elapsed format like "X days ago".

<?php
class Time {
    const DAY = 24 * self::HOUR;
    const HOUR = 60 * self::MINUTE;
    const MINUTE = 60 * self::SECOND;
    const SECOND = 1;

    public static function formatOld($time) {
        $result = '';

        $diff = $time - microtime(true);
        $future = $diff > 0;
        $diff = abs($diff);

        if ($diff == 0) {
            return 'now';
        } else if ($diff >= self::DAY) {
            $result = floor($diff / self::DAY) . 'd';
        } else if ($diff >= self::HOUR) {
            $result = floor($diff / self::HOUR) . 'h';
        } else if ($diff >= self::MINUTE) {
            $result = floor($diff / self::MINUTE) . 'm';
        } else if ($diff >= self::SECOND) {
            $result = floor($diff / self::SECOND) . 's';
        } else if ($diff >= self::SECOND) {
            $result = $diff . 's';
        }

        $result .= $future ? ' in the future' : ' ago';
        return $result;
    }
}

Previous snippet | Next snippet