Commit c773be2f authored by Jens Segers's avatar Jens Segers

Improving date conversions

parent 76f62009
......@@ -92,19 +92,19 @@ abstract class Model extends \Jenssegers\Eloquent\Model {
*/
public function fromDateTime($value)
{
// Convert DateTime to MongoDate
if ($value instanceof DateTime)
// If the value is already a MongoDate instance, we don't need to parse it.
if ($value instanceof MongoDate)
{
$value = new MongoDate($value->getTimestamp());
return $value;
}
// Convert timestamp to MongoDate
elseif (is_numeric($value))
// Let Eloquent convert the value to a DateTime instance.
if ( ! $value instanceof DateTime)
{
$value = new MongoDate($value);
$value = parent::asDateTime($value);
}
return $value;
return new MongoDate($value->getTimestamp());
}
/**
......@@ -115,25 +115,13 @@ abstract class Model extends \Jenssegers\Eloquent\Model {
*/
protected function asDateTime($value)
{
// Convert timestamp
if (is_numeric($value))
{
return Carbon::createFromTimestamp($value);
}
// Convert string
if (is_string($value))
{
return new Carbon($value);
}
// Convert MongoDate
// Convert MongoDate instances.
if ($value instanceof MongoDate)
{
return Carbon::createFromTimestamp($value->sec);
}
return Carbon::instance($value);
return parent::asDateTime($value);
}
/**
......
......@@ -331,13 +331,22 @@ class ModelTest extends TestCase {
// test custom date format for json output
$json = $user->toArray();
$this->assertEquals($user->birthday->format('U'), $json['birthday']);
$this->assertEquals($user->created_at->format('U'), $json['created_at']);
$this->assertEquals($user->birthday->format('l jS \of F Y h:i:s A'), $json['birthday']);
$this->assertEquals($user->created_at->format('l jS \of F Y h:i:s A'), $json['created_at']);
// test default date format for json output
$item = Item::create(array('name' => 'sword'));
$json = $item->toArray();
$this->assertEquals($item->created_at->format('Y-m-d H:i:s'), $json['created_at']);
$user = User::create(array('name' => 'Jane Doe', 'birthday' => time()));
$this->assertInstanceOf('Carbon\Carbon', $user->birthday);
$user = User::create(array('name' => 'Jane Doe', 'birthday' => 'Monday 8th of August 2005 03:12:46 PM'));
$this->assertInstanceOf('Carbon\Carbon', $user->birthday);
$user = User::create(array('name' => 'Jane Doe', 'birthday' => '2005-08-08'));
$this->assertInstanceOf('Carbon\Carbon', $user->birthday);
}
public function testIdAttribute()
......
......@@ -87,6 +87,6 @@ class User extends Eloquent implements UserInterface, RemindableInterface {
protected function getDateFormat()
{
return 'U';
return 'l jS \of F Y h:i:s A';
}
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment