Tools\Utility\Time::niceDate PHP Method

niceDate() public static method

Options: - timezone: User's timezone - default: Default string (defaults to "-----") - oclock: Set to true to append oclock string
public static niceDate ( 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 Options
return string
    public static function niceDate($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 ($options['timezone']) {
            $options['timezone'] = static::safeCreateDateTimeZone($options['timezone']);
        }
        if ($dateString === null) {
            return $options['default'];
        }
        if (!is_object($dateString)) {
            $date = new DateTime($dateString, $options['timezone']);
        } else {
            $date = $dateString;
        }
        $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_NICE_YMDHM;
            } else {
                $format = FORMAT_NICE_YMD;
            }
        }
        $ret = date($format, $date);
        if (!empty($options['oclock'])) {
            switch ($format) {
                case FORMAT_NICE_YMDHM:
                case FORMAT_NICE_YMDHMS:
                case FORMAT_NICE_HM:
                case FORMAT_NICE_HMS:
                    $ret .= ' ' . __d('tools', 'o\'clock');
                    break;
            }
        }
        return $ret;
    }

Usage Example

Exemplo n.º 1
0
 /**
  * Test that input as date only (YYYY-MM-DD) does not suddendly return a
  * different date on output due to timezone differences.
  * Here the timezone should not apply since we only input date and only output
  * date (time itself is irrelevant).
  *
  * @return void
  */
 public function testDateWithTimezone()
 {
     $res = setlocale(LC_TIME, 'de_DE.UTF-8', 'deu_deu');
     //$this->assertTrue(!empty($res));
     Configure::write('Config.timezone', 'America/Anchorage');
     $ret = $this->Time->niceDate('2009-12-01');
     //debug($ret);
     $this->assertEquals('01.12.2009', $ret);
     $ret = $this->Time->localDate('2009-12-01');
     //debug($ret);
     $this->assertEquals('01.12.2009', $ret);
 }