Skip to content

Commit

Permalink
Browse files Browse the repository at this point in the history
added option to set json_encode formatting using setJsonEncodeFormat
  • Loading branch information
segy committed Aug 14, 2015
1 parent 5643708 commit f99cb79
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 2 deletions.
29 changes: 28 additions & 1 deletion src/I18n/Time.php
Expand Up @@ -44,6 +44,22 @@ class Time extends Carbon implements JsonSerializable
*/
protected static $_toStringFormat = [IntlDateFormatter::SHORT, IntlDateFormatter::SHORT];

/**
* The format to use when when converting this object to json
*
* The format should be either the formatting constants from IntlDateFormatter as
* described in (http://www.php.net/manual/en/class.intldateformatter.php) or a pattern
* as specified in (http://www.icu-project.org/apiref/icu4c/classSimpleDateFormat.html#details)
*
* It is possible to provide an array of 2 constants. In this case, the first position
* will be used for formatting the date part of the object and the second position
* will be used to format the time part.
*
* @var mixed
* @see \Cake\I18n\Time::i18nFormat()
*/
protected static $_jsonEncodeFormat = "yyyy-MM-dd'T'HH:mm:ssxx";

/**
* The format to use when formatting a time using `Cake\I18n\Time::nice()`
*
Expand Down Expand Up @@ -680,6 +696,17 @@ public static function setToStringFormat($format)
static::$_toStringFormat = $format;
}

/**
* Sets the default format used when converting this object to json
*
* @param string|array|int $format Format.
* @return void
*/
public static function setJsonEncodeFormat($format)
{
static::$_jsonEncodeFormat = $format;
}

/**
* Returns a new Time object after parsing the provided time string based on
* the passed or configured date time format. This method is locale dependent,
Expand Down Expand Up @@ -799,7 +826,7 @@ public static function parseTime($time, $format = null)
*/
public function jsonSerialize()
{
return $this->format(static::ISO8601);
return $this->i18nFormat(static::$_jsonEncodeFormat);
}

/**
Expand Down
4 changes: 3 additions & 1 deletion tests/TestCase/I18n/TimeTest.php
Expand Up @@ -191,7 +191,7 @@ public function testTimeAgoInWordsTimezone()
);
$this->assertEquals('on 31-07-1990 13:33:00', $result);
}

/**
* test the end option for timeAgoInWords
*
Expand Down Expand Up @@ -688,6 +688,8 @@ public function testJsonEnconde()
{
$time = new Time('2014-04-20 10:10:10');
$this->assertEquals('"2014-04-20T10:10:10+0000"', json_encode($time));
Time::setJsonEncodeFormat('yyyy-MM-dd HH:mm:ss');
$this->assertEquals('"2014-04-20 10:10:10"', json_encode($time));
}

/**
Expand Down

0 comments on commit f99cb79

Please sign in to comment.