Versions
Look up a class, method, property or event

CDateFormatter

Package system.i18n
Inheritance class CDateFormatter » CComponent
Since 1.0
Source Code framework/i18n/CDateFormatter.php
CDateFormatter provides date/time localization functionalities.

CDateFormatter allows you to format dates and times in a locale-sensitive manner. Patterns are interpreted in the locale that the CDateFormatter instance is associated with. For example, month names and weekday names may vary under different locales, which yields different formatting results. The patterns that CDateFormatter recognizes are as defined in CLDR.

CDateFormatter supports predefined patterns as well as customized ones:

Public Methods

Hide inherited methods

MethodDescriptionDefined By
__call() Calls the named method which is not a class method. CComponent
__construct() Constructor. CDateFormatter
__get() Returns a property value, an event handler list or a behavior based on its name. CComponent
__isset() Checks if a property value is null. CComponent
__set() Sets value of a component property. CComponent
__unset() Sets a component property to be null. CComponent
asa() Returns the named behavior object. CComponent
attachBehavior() Attaches a behavior to this component. CComponent
attachBehaviors() Attaches a list of behaviors to the component. CComponent
attachEventHandler() Attaches an event handler to an event. CComponent
canGetProperty() Determines whether a property can be read. CComponent
canSetProperty() Determines whether a property can be set. CComponent
detachBehavior() Detaches a behavior from the component. CComponent
detachBehaviors() Detaches all behaviors from the component. CComponent
detachEventHandler() Detaches an existing event handler. CComponent
disableBehavior() Disables an attached behavior. CComponent
disableBehaviors() Disables all behaviors attached to this component. CComponent
enableBehavior() Enables an attached behavior. CComponent
enableBehaviors() Enables all behaviors attached to this component. CComponent
evaluateExpression() Evaluates a PHP expression or callback under the context of this component. CComponent
format() Formats a date according to a customized pattern. CDateFormatter
formatDateTime() Formats a date according to a predefined pattern. CDateFormatter
getEventHandlers() Returns the list of attached event handlers for an event. CComponent
hasEvent() Determines whether an event is defined. CComponent
hasEventHandler() Checks whether the named event has attached handlers. CComponent
hasProperty() Determines whether a property is defined. CComponent
raiseEvent() Raises an event. CComponent

Protected Methods

Hide inherited methods

MethodDescriptionDefined By
formatDay() Get the day of the month. CDateFormatter
formatDayInMonth() Get day of week in the month, e.g. 2nd Wed in July. CDateFormatter
formatDayInWeek() Get the day of the week. CDateFormatter
formatDayInYear() Get the day in the year, e.g. [1-366] CDateFormatter
formatEra() Get the era. i.e. in gregorian, year > 0 is AD, else BC. CDateFormatter
formatHour12() Get the hours in 12 hour format, i.e., [1-12] CDateFormatter
formatHour24() Get the hours in 24 hour format, i.e. [0-23]. CDateFormatter
formatHourInDay() Get the hours [1-24]. CDateFormatter
formatHourInPeriod() Get the hours in AM/PM format, e.g [0-11] CDateFormatter
formatMinutes() Get the minutes. CDateFormatter
formatMonth() Get the month. CDateFormatter
formatPeriod() Get the AM/PM designator, 12 noon is PM, 12 midnight is AM. CDateFormatter
formatSeconds() Get the seconds. CDateFormatter
formatTimeZone() Get the timezone of the server machine. CDateFormatter
formatWeekInMonth() Get week in the month. CDateFormatter
formatWeekInYear() Get the week in the year. CDateFormatter
formatYear() Get the year. CDateFormatter
parseFormat() Parses the datetime format pattern. CDateFormatter

Method Details

__construct() method
public void __construct(mixed $locale)
$locale mixed locale ID (string) or CLocale instance
Source Code: framework/i18n/CDateFormatter.php#72 (show)
public function __construct($locale)
{
    if(
is_string($locale))
        
$this->_locale=CLocale::getInstance($locale);
    else
        
$this->_locale=$locale;
}

Constructor.

format() method
public string format(string $pattern, mixed $time)
$pattern string the pattern (See http://www.unicode.org/reports/tr35/tr35-dates.html#Date_Format_Patterns)
$time mixed UNIX timestamp or a string in strtotime format
{return} string formatted date time. Null if $time is null. (the null value check is available since Yii 1.1.11)
Source Code: framework/i18n/CDateFormatter.php#86 (show)
public function format($pattern,$time)
{
    if(
$time===null)
        return 
null;

    if(
is_string($time))
    {
        if(
ctype_digit($time) || ($time{0}=='-' && ctype_digit(substr($time1))))
            
$time=(int)$time;
        else
            
$time=strtotime($time);
    }
    
$date=CTimestamp::getDate($time,false,false);
    
$tokens=$this->parseFormat($pattern);
    foreach(
$tokens as &$token)
    {
        if(
is_array($token)) // a callback: method name, sub-pattern
            
$token=$this->{$token[0]}($token[1],$date);
    }
    return 
implode('',$tokens);
}

Formats a date according to a customized pattern.

formatDateTime() method
public string formatDateTime(mixed $timestamp, string $dateWidth='medium', string $timeWidth='medium')
$timestamp mixed UNIX timestamp or a string in strtotime format
$dateWidth string width of the date pattern. It can be 'full', 'long', 'medium' and 'short'. If null, it means the date portion will NOT appear in the formatting result
$timeWidth string width of the time pattern. It can be 'full', 'long', 'medium' and 'short'. If null, it means the time portion will NOT appear in the formatting result
{return} string formatted date time.
Source Code: framework/i18n/CDateFormatter.php#118 (show)
public function formatDateTime($timestamp,$dateWidth='medium',$timeWidth='medium')
{
    if(!empty(
$dateWidth))
        
$date=$this->format($this->_locale->getDateFormat($dateWidth),$timestamp);

    if(!empty(
$timeWidth))
        
$time=$this->format($this->_locale->getTimeFormat($timeWidth),$timestamp);

    if(isset(
$date) && isset($time))
    {
        
$dateTimePattern=$this->_locale->getDateTimeFormat();
        return 
strtr($dateTimePattern,array('{0}'=>$time,'{1}'=>$date));
    }
    elseif(isset(
$date))
        return 
$date;
    elseif(isset(
$time))
        return 
$time;
}

Formats a date according to a predefined pattern. The predefined pattern is determined based on the date pattern width and time pattern width.

formatDay() method
protected string formatDay(string $pattern, array $date)
$pattern string a pattern.
$date array result of CTimestamp::getdate.
{return} string day of the month
Source Code: framework/i18n/CDateFormatter.php#263 (show)
protected function formatDay($pattern,$date)
{
    
$day=$date['mday'];
    if(
$pattern==='d')
        return 
$day;
    elseif(
$pattern==='dd')
        return 
str_pad($day,2,'0',STR_PAD_LEFT);
    else
        throw new 
CException(Yii::t('yii','The pattern for day of the month must be "d" or "dd".'));
}

Get the day of the month. "d" for non-padding, "dd" will always return 2 digits day numbers, e.g. 05.

formatDayInMonth() method
protected integer formatDayInMonth(string $pattern, array $date)
$pattern string a pattern.
$date array result of CTimestamp::getdate.
{return} integer day in month
Source Code: framework/i18n/CDateFormatter.php#298 (show)
protected function formatDayInMonth($pattern,$date)
{
    if(
$pattern==='F')
        return (int)((
$date['mday']+6)/7);
    else
        throw new 
CException(Yii::t('yii','The pattern for day in month must be "F".'));
}

Get day of week in the month, e.g. 2nd Wed in July.

formatDayInWeek() method
protected string formatDayInWeek(string $pattern, array $date)
$pattern string a pattern.
$date array result of CTimestamp::getdate.
{return} string day of the week.
Source Code: framework/i18n/CDateFormatter.php#317 (show)
protected function formatDayInWeek($pattern,$date)
{
    
$day=$date['wday'];
    switch(
$pattern)
    {
        case 
'E':
        case 
'EE':
        case 
'EEE':
        case 
'eee':
            return 
$this->_locale->getWeekDayName($day,'abbreviated');
        case 
'EEEE':
        case 
'eeee':
            return 
$this->_locale->getWeekDayName($day,'wide');
        case 
'EEEEE':
        case 
'eeeee':
            return 
$this->_locale->getWeekDayName($day,'narrow');
        case 
'e':
        case 
'ee':
        case 
'c':
            return 
$day $day 7;
        case 
'ccc':
            return 
$this->_locale->getWeekDayName($day,'abbreviated',true);
        case 
'cccc':
            return 
$this->_locale->getWeekDayName($day,'wide',true);
        case 
'ccccc':
            return 
$this->_locale->getWeekDayName($day,'narrow',true);
        default:
            throw new 
CException(Yii::t('yii','The pattern for day of the week must be "E", "EE", "EEE", "EEEE", "EEEEE", "e", "ee", "eee", "eeee", "eeeee", "c", "cccc" or "ccccc".'));
    }
}

Get the day of the week. "E", "EE", "EEE" will return abbreviated week day name, e.g. "Tues"; "EEEE" will return full week day name; "EEEEE" will return the narrow week day name, e.g. "T";

formatDayInYear() method
protected integer formatDayInYear(string $pattern, array $date)
$pattern string a pattern.
$date array result of CTimestamp::getdate.
{return} integer hours in AM/PM format.
Source Code: framework/i18n/CDateFormatter.php#281 (show)
protected function formatDayInYear($pattern,$date)
{
    
$day=$date['yday'];
    if((
$n=strlen($pattern))<=3)
        return 
str_pad($day,$n,'0',STR_PAD_LEFT);
    else
        throw new 
CException(Yii::t('yii','The pattern for day in year must be "D", "DD" or "DDD".'));
}

Get the day in the year, e.g. [1-366]

formatEra() method
protected string formatEra(string $pattern, array $date)
$pattern string a pattern.
$date array result of CTimestamp::getdate.
{return} string era
Source Code: framework/i18n/CDateFormatter.php#542 (show)
protected function formatEra($pattern,$date)
{
    
$era=$date['year']>0;
    switch(
$pattern)
    {
        case 
'G':
        case 
'GG':
        case 
'GGG':
            return 
$this->_locale->getEraName($era,'abbreviated');
        case 
'GGGG':
            return 
$this->_locale->getEraName($era,'wide');
        case 
'GGGGG':
            return 
$this->_locale->getEraName($era,'narrow');
        default:
            throw new 
CException(Yii::t('yii','The pattern for era must be "G", "GG", "GGG", "GGGG" or "GGGGG".'));
    }
}

Get the era. i.e. in gregorian, year > 0 is AD, else BC.

formatHour12() method
protected string formatHour12(string $pattern, array $date)
$pattern string a pattern.
$date array result of CTimestamp::getdate.
{return} string hours in 12 hour format.
Source Code: framework/i18n/CDateFormatter.php#395 (show)
protected function formatHour12($pattern,$date)
{
    
$hour=$date['hours'];
    
$hour=($hour==12|$hour==0)?12:($hour)%12;
    if(
$pattern==='h')
        return 
$hour;
    elseif(
$pattern==='hh')
        return 
str_pad($hour,2,'0',STR_PAD_LEFT);
    else
        throw new 
CException(Yii::t('yii','The pattern for 12 hour format must be "h" or "hh".'));
}

Get the hours in 12 hour format, i.e., [1-12] "h" for non-padding, "hh" will always return 2 characters.

formatHour24() method
protected string formatHour24(string $pattern, array $date)
$pattern string a pattern.
$date array result of CTimestamp::getdate.
{return} string hours in 24 hour format.
Source Code: framework/i18n/CDateFormatter.php#376 (show)
protected function formatHour24($pattern,$date)
{
    
$hour=$date['hours'];
    if(
$pattern==='H')
        return 
$hour;
    elseif(
$pattern==='HH')
        return 
str_pad($hour,2,'0',STR_PAD_LEFT);
    else
        throw new 
CException(Yii::t('yii','The pattern for 24 hour format must be "H" or "HH".'));
}

Get the hours in 24 hour format, i.e. [0-23]. "H" for non-padding, "HH" will always return 2 characters.

formatHourInDay() method
protected integer formatHourInDay(string $pattern, array $date)
$pattern string a pattern.
$date array result of CTimestamp::getdate.
{return} integer hours [1-24]
Source Code: framework/i18n/CDateFormatter.php#415 (show)
protected function formatHourInDay($pattern,$date)
{
    
$hour=$date['hours']==0?24:$date['hours'];
    if(
$pattern==='k')
        return 
$hour;
    elseif(
$pattern==='kk')
        return 
str_pad($hour,2,'0',STR_PAD_LEFT);
    else
        throw new 
CException(Yii::t('yii','The pattern for hour in day must be "k" or "kk".'));
}

Get the hours [1-24]. 'k' for non-padding, and 'kk' with 2 characters padding.

formatHourInPeriod() method
protected integer formatHourInPeriod(string $pattern, array $date)
$pattern string a pattern.
$date array result of CTimestamp::getdate.
{return} integer hours in AM/PM format.
Source Code: framework/i18n/CDateFormatter.php#434 (show)
protected function formatHourInPeriod($pattern,$date)
{
    
$hour=$date['hours']%12;
    if(
$pattern==='K')
        return 
$hour;
    elseif(
$pattern==='KK')
        return 
str_pad($hour,2,'0',STR_PAD_LEFT);
    else
        throw new 
CException(Yii::t('yii','The pattern for hour in AM/PM must be "K" or "KK".'));
}

Get the hours in AM/PM format, e.g [0-11] "K" for non-padding, "KK" will always return 2 characters.

formatMinutes() method
protected string formatMinutes(string $pattern, array $date)
$pattern string a pattern.
$date array result of CTimestamp::getdate.
{return} string minutes.
Source Code: framework/i18n/CDateFormatter.php#453 (show)
protected function formatMinutes($pattern,$date)
{
    
$minutes=$date['minutes'];
    if(
$pattern==='m')
        return 
$minutes;
    elseif(
$pattern==='mm')
        return 
str_pad($minutes,2,'0',STR_PAD_LEFT);
    else
        throw new 
CException(Yii::t('yii','The pattern for minutes must be "m" or "mm".'));
}

Get the minutes. "m" for non-padding, "mm" will always return 2 characters.

formatMonth() method
protected string formatMonth(string $pattern, array $date)
$pattern string a pattern.
$date array result of CTimestamp::getdate.
{return} string month name
Source Code: framework/i18n/CDateFormatter.php#225 (show)
protected function formatMonth($pattern,$date)
{
    
$month=$date['mon'];
    switch(
$pattern)
    {
        case 
'M':
            return 
$month;
        case 
'MM':
            return 
str_pad($month,2,'0',STR_PAD_LEFT);
        case 
'MMM':
            return 
$this->_locale->getMonthName($month,'abbreviated');
        case 
'MMMM':
            return 
$this->_locale->getMonthName($month,'wide');
        case 
'MMMMM':
            return 
$this->_locale->getMonthName($month,'narrow');
        case 
'L':
            return 
$month;
        case 
'LL':
            return 
str_pad($month,2,'0',STR_PAD_LEFT);
        case 
'LLL':
            return 
$this->_locale->getMonthName($month,'abbreviated'true);
        case 
'LLLL':
            return 
$this->_locale->getMonthName($month,'wide'true);
        case 
'LLLLL':
            return 
$this->_locale->getMonthName($month,'narrow'true);
        default:
            throw new 
CException(Yii::t('yii','The pattern for month must be "M", "MM", "MMM", "MMMM", "L", "LL", "LLL" or "LLLL".'));
    }
}

Get the month. "M" will return integer 1 through 12; "MM" will return two digits month number with necessary zero padding, e.g. 05; "MMM" will return the abrreviated month name, e.g. "Jan"; "MMMM" will return the full month name, e.g. "January"; "MMMMM" will return the narrow month name, e.g. "J";

formatPeriod() method
protected string formatPeriod(string $pattern, array $date)
$pattern string a pattern.
$date array result of CTimestamp::getdate.
{return} string AM or PM designator
Source Code: framework/i18n/CDateFormatter.php#355 (show)
protected function formatPeriod($pattern,$date)
{
    if(
$pattern==='a')
    {
        if(
intval($date['hours']/12))
            return 
$this->_locale->getPMName();
        else
            return 
$this->_locale->getAMName();
    }
    else
        throw new 
CException(Yii::t('yii','The pattern for AM/PM marker must be "a".'));
}

Get the AM/PM designator, 12 noon is PM, 12 midnight is AM.

formatSeconds() method
protected string formatSeconds(string $pattern, array $date)
$pattern string a pattern.
$date array result of CTimestamp::getdate.
{return} string seconds
Source Code: framework/i18n/CDateFormatter.php#472 (show)
protected function formatSeconds($pattern,$date)
{
    
$seconds=$date['seconds'];
    if(
$pattern==='s')
        return 
$seconds;
    elseif(
$pattern==='ss')
        return 
str_pad($seconds,2,'0',STR_PAD_LEFT);
    else
        throw new 
CException(Yii::t('yii','The pattern for seconds must be "s" or "ss".'));
}

Get the seconds. "s" for non-padding, "ss" will always return 2 characters.

formatTimeZone() method
protected string formatTimeZone(string $pattern, array $date)
$pattern string a pattern.
$date array result of CTimestamp::getdate.
{return} string time zone
Source Code: framework/i18n/CDateFormatter.php#524 (show)
protected function formatTimeZone($pattern,$date)
{
    if(
$pattern[0]==='z' || $pattern[0]==='v')
        return @
date('T', @mktime($date['hours'], $date['minutes'], $date['seconds'], $date['mon'], $date['mday'], $date['year']));
    elseif(
$pattern[0]==='Z')
        return @
date('O', @mktime($date['hours'], $date['minutes'], $date['seconds'], $date['mon'], $date['mday'], $date['year']));
    else
        throw new 
CException(Yii::t('yii','The pattern for time zone must be "z" or "v".'));
}

Get the timezone of the server machine.

formatWeekInMonth() method
protected integer formatWeekInMonth(array $pattern, string $date)
$pattern array result of CTimestamp::getdate.
$date string a pattern.
{return} integer week in month
Source Code: framework/i18n/CDateFormatter.php#505 (show)
protected function formatWeekInMonth($pattern,$date)
{
    if(
$pattern==='W')
    {
        
$weekDay=date('N',mktime(0,0,0,$date['mon'],1,$date['year']));
        return 
floor(($weekDay+$date['mday']-2)/7)+1;
    }
    else
        throw new 
CException(Yii::t('yii','The pattern for week in month must be "W".'));
}

Get week in the month.

formatWeekInYear() method
protected integer formatWeekInYear(string $pattern, array $date)
$pattern string a pattern.
$date array result of CTimestamp::getdate.
{return} integer week in year
Source Code: framework/i18n/CDateFormatter.php#490 (show)
protected function formatWeekInYear($pattern,$date)
{
    if(
$pattern==='w')
        return @
date('W',@mktime(0,0,0,$date['mon'],$date['mday'],$date['year']));
    else
        throw new 
CException(Yii::t('yii','The pattern for week in year must be "w".'));
}

Get the week in the year.

formatYear() method
protected string formatYear(string $pattern, array $date)
$pattern string a pattern.
$date array result of CTimestamp::getdate.
{return} string formatted year
Source Code: framework/i18n/CDateFormatter.php#204 (show)
protected function formatYear($pattern,$date)
{
    
$year=$date['year'];
    if(
$pattern==='yy')
        return 
str_pad($year%100,2,'0',STR_PAD_LEFT);
    else
        return 
str_pad($year,strlen($pattern),'0',STR_PAD_LEFT);
}

Get the year. "yy" will return the last two digits of year. "y...y" will pad the year with 0 in the front, e.g. "yyyyy" will generate "02008" for year 2008.

parseFormat() method
protected array parseFormat(string $pattern)
$pattern string the pattern to be parsed
{return} array tokenized parsing result
Source Code: framework/i18n/CDateFormatter.php#142 (show)
protected function parseFormat($pattern)
{
    static 
$formats=array();  // cache
    
if(isset($formats[$pattern]))
        return 
$formats[$pattern];
    
$tokens=array();
    
$n=strlen($pattern);
    
$isLiteral=false;
    
$literal='';
    for(
$i=0;$i<$n;++$i)
    {
        
$c=$pattern[$i];
        if(
$c==="'")
        {
            if(
$i<$n-&& $pattern[$i+1]==="'")
            {
                
$tokens[]="'";
                
$i++;
            }
            elseif(
$isLiteral)
            {
                
$tokens[]=$literal;
                
$literal='';
                
$isLiteral=false;
            }
            else
            {
                
$isLiteral=true;
                
$literal='';
            }
        }
        elseif(
$isLiteral)
            
$literal.=$c;
        else
        {
            for(
$j=$i+1;$j<$n;++$j)
            {
                if(
$pattern[$j]!==$c)
                    break;
            }
            
$p=str_repeat($c,$j-$i);
            if(isset(
self::$_formatters[$c]))
                
$tokens[]=array(self::$_formatters[$c],$p);
            else
                
$tokens[]=$p;
            
$i=$j-1;
        }
    }
    if(
$literal!=='')
        
$tokens[]=$literal;

    return 
$formats[$pattern]=$tokens;
}

Parses the datetime format pattern.

Total 2 comments

#11297 report it
marcovtwout at 2013/01/04 05:19am
Using dateFormatter

The dateFormatter is registered as a component through CApplication. You can use it like this:

Yii::app()->dateFormatter->formatDateTime($model->createdOn, 'long', null)
#10006 report it
Mike at 2012/09/28 06:25am
What the formats in formatDateTime() mean

Here's some example output of Yii::app()->dateFormatter->formatDateTime($time, $formatDate, $formatTime) for locale en_GB:

$formatDate/$formatTimeDateTime
fullMonday, 23 April 201216:09:04 UTC
long23 April 201216:12:14 UTC
medium23 Apr 201216:12:46
short23/04/201216:13

Leave a comment

Please to leave your comment.