Skip to content

Commit

Permalink
added Dater::getLocaleByCode($code)
Browse files Browse the repository at this point in the history
  • Loading branch information
barbushin committed Mar 22, 2013
1 parent c594684 commit 45154db
Show file tree
Hide file tree
Showing 4 changed files with 24 additions and 2 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -161,3 +161,4 @@ pip-log.txt

# Mac crap
.DS_Store
.idea
21 changes: 21 additions & 0 deletions Dater/Dater.php
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,12 @@ class Dater {
const SERVER_TIME_FORMAT = 'server_time';
const SERVER_DATETIME_FORMAT = 'server_datetime';

protected static $localesCodes = array(
'en' => 'English',
'ru' => 'Russian',
'ua' => 'Ukrainian',
);

protected $formats = array(
self::USER_DATE_FORMAT => 'm/d/Y',
self::USER_TIME_FORMAT => 'g:i A',
Expand Down Expand Up @@ -50,6 +56,21 @@ public function getLocale() {
return $this->locale;
}

/**
* Get locale by 2-chars code: en, ru, ua
* @param $code
* @throws Exception
* @return
*/
public static function getLocaleByCode($code) {
$code = strtolower($code);
if(!isset(static::$localesCodes[$code])) {
throw new Exception('Unknown locale code "' . $code . '". See available codes in Dater::$localeCodes.');
}
$class = 'Dater_Locale_' . static::$localesCodes[$code];
return new $class();
}

public function setLocale(Dater_Locale $locale) {
foreach($locale::$formats as $alias => $format) {
$this->setFormat($alias, $format);
Expand Down
2 changes: 1 addition & 1 deletion example/index.php
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@
echo 'User date: ' . $dater->date() . PHP_EOL;
echo 'User formatted date: ' . $dater->now('j F Y') . PHP_EOL . PHP_EOL;

$dater->setLocale(new Dater_Locale_Russian());
$dater->setLocale(Dater::getLocaleByCode('ru'));
echo 'Set locale: : ' . get_class($dater->getLocale()) . PHP_EOL;
echo 'User date: ' . $dater->date() . PHP_EOL;
echo 'User formatted date: ' . $dater->now('j F Y') . PHP_EOL . PHP_EOL;
Expand Down
2 changes: 1 addition & 1 deletion readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ All [date()](http://php.net/date) format options available and can be overrided

### Locales support

$dater->setLocale(new Dater_Locale_English());
$dater->setLocale(new Dater_Locale_English()); // or you can use Dater::getLocaleByCode('ru')
echo $dater->date(); // 03/21/2013
echo $dater->now('j F Y'); // 21 March 2013

Expand Down

0 comments on commit 45154db

Please sign in to comment.