Tools\Utility\Time::relLengthOfTime PHP Method

relLengthOfTime() public static method

Time relative to NOW in human readable format - absolute (negative as well as positive) TODO: make "now" adjustable
public static relLengthOfTime ( mixed $date, string | null $format = null, array $options = [] ) : string
$date mixed
$format string | null Format
$options array Options - default, separator - boolean zero: if false: 0 days 5 hours => 5 hours etc. - verbose/past/future: string with %s or boolean true/false
return string
    public static function relLengthOfTime($date, $format = null, array $options = [])
    {
        if ($date !== null && !is_object($date)) {
            $date = static::parse($date);
        }
        if ($date !== null) {
            $date = $date->format('U');
            $sec = time() - $date;
            $type = $sec > 0 ? -1 : ($sec < 0 ? 1 : 0);
            $sec = abs($sec);
        } else {
            $sec = 0;
            $type = 0;
        }
        $defaults = ['verbose' => __d('tools', 'justNow'), 'zero' => false, 'separator' => ', ', 'future' => __d('tools', 'In %s'), 'past' => __d('tools', '%s ago'), 'default' => ''];
        $options += $defaults;
        $ret = static::lengthOfTime($sec, $format, $options);
        if ($type == 1) {
            if ($options['future'] !== false) {
                return sprintf($options['future'], $ret);
            }
            return ['future' => $ret];
        }
        if ($type == -1) {
            if ($options['past'] !== false) {
                return sprintf($options['past'], $ret);
            }
            return ['past' => $ret];
        }
        if ($options['verbose'] !== false) {
            return $options['verbose'];
        }
        return $options['default'];
    }

Usage Example

Ejemplo n.º 1
0
 /**
  * TimeTest::testRelLengthOfTime()
  *
  * @return void
  */
 public function testRelLengthOfTime()
 {
     $ret = $this->Time->relLengthOfTime('1990-11-20');
     //pr($ret);
     $ret = $this->Time->relLengthOfTime('2012-11-20');
     //pr($ret);
     $res = $this->Time->relLengthOfTime(date(FORMAT_DB_DATETIME, time() - 3600));
     //pr($res);
     $this->assertTrue(!empty($res));
     $res = $this->Time->relLengthOfTime(date(FORMAT_DB_DATETIME, time() - 4 * DAY - 5 * HOUR), null, ['plural' => 'n']);
     //pr($res);
     //$this->assertEquals($res, 'Vor 4 Tagen, 5 '.__d('tools', 'Hours'));
     $this->assertEquals(__d('tools', '{0} ago', '4 ' . __d('tools', 'Days') . ', ' . '5 ' . __d('tools', 'Hours')), $res);
     $res = $this->Time->relLengthOfTime(date(FORMAT_DB_DATETIME, time() + 4 * DAY + 5 * HOUR), null, ['plural' => 'n']);
     //pr($res);
     $this->assertEquals(__d('tools', 'In {0}', '4 ' . __d('tools', 'Days') . ', ' . '5 ' . __d('tools', 'Hours')), $res);
     $res = $this->Time->relLengthOfTime(date(FORMAT_DB_DATETIME, time()), null, ['plural' => 'n']);
     //pr($res);
     $this->assertEquals($res, __d('tools', 'justNow'));
 }