Tools\Utility\Time::localDate PHP Method

localDate() public static method

Options: - timezone: User's timezone - default: Default string (defaults to "-----") - oclock: Set to true to append oclock string
public static localDate ( string | null $dateString = null, string | null $format = null, array $options = [] ) : string
$dateString string | null
$format string | null Format (YYYY-MM-DD, DD.MM.YYYY)
$options array
return string
    public static function localDate($dateString = null, $format = null, array $options = [])
    {
        $defaults = ['default' => '-----', 'timezone' => null];
        $options += $defaults;
        if ($options['timezone'] === null && strlen($dateString) === 10) {
            $options['timezone'] = date_default_timezone_get();
        }
        if ($dateString === null) {
            $dateString = time();
        }
        if ($options['timezone']) {
            $options['timezone'] = static::safeCreateDateTimeZone($options['timezone']);
        }
        $date = new DateTime($dateString, $options['timezone']);
        $date = $date->format('U');
        if ($date === null || $date === false || $date <= 0) {
            return $options['default'];
        }
        if ($format === null) {
            if (is_int($dateString) || strpos($dateString, ' ') !== false) {
                $format = FORMAT_LOCAL_YMDHM;
            } else {
                $format = FORMAT_LOCAL_YMD;
            }
        }
        $date = static::_strftime($format, $date);
        if (!empty($options['oclock'])) {
            switch ($format) {
                case FORMAT_LOCAL_YMDHM:
                case FORMAT_LOCAL_YMDHMS:
                case FORMAT_LOCAL_HM:
                case FORMAT_LOCAL_HMS:
                    $date .= ' ' . __d('tools', 'o\'clock');
                    break;
            }
        }
        return $date;
    }

Usage Example

Beispiel #1
0
 /**
  * TimeTest::testLocalDate()
  *
  * @return void
  */
 public function testLocalDate()
 {
     $this->skipIf(PHP_SAPI === 'cli', 'for now');
     $res = setlocale(LC_TIME, ['de_DE.UTF-8', 'deu_deu']);
     $this->assertTrue(!empty($res));
     $values = [['2009-12-01 00:00:00', FORMAT_LOCAL_YMD, '01.12.2009'], ['2009-12-01 00:00:00', FORMAT_LOCAL_M_FULL, 'Dezember']];
     foreach ($values as $v) {
         $ret = $this->Time->localDate($v[0], $v[1]);
         //$this->debug($ret);
         $this->assertEquals($v[2], $ret);
     }
     $date = '2009-12-01 00:00:00';
     $format = FORMAT_LOCAL_YMD;
     $result = $this->Time->localDate($date, $format, ['oclock' => true]);
     $expected = '01.12.2009';
     $this->assertEquals($expected, $result);
     $date = '2009-12-01 00:00:00';
     $format = FORMAT_LOCAL_YMDHM;
     $result = $this->Time->localDate($date, $format, ['oclock' => true]);
     $expected = '01.12.2009, 00:00 ' . __d('tools', 'o\'clock');
     $this->assertEquals($expected, $result);
 }