Skip to content

Commit 3c0edb0

Browse files
committed
Tweaking date format for json output
1 parent c2fb55c commit 3c0edb0

File tree

3 files changed

+28
-2
lines changed

3 files changed

+28
-2
lines changed

src/Jenssegers/Mongodb/Model.php

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -136,6 +136,16 @@ protected function asDateTime($value)
136136
return Carbon::instance($value);
137137
}
138138

139+
/**
140+
* Get the format for database stored dates.
141+
*
142+
* @return string
143+
*/
144+
protected function getDateFormat()
145+
{
146+
return 'Y-m-d H:i:s';
147+
}
148+
139149
/**
140150
* Get a fresh timestamp for the model.
141151
*
@@ -206,7 +216,7 @@ public function attributesToArray()
206216
*/
207217
if ($value instanceof MongoDate)
208218
{
209-
$value = $this->asDateTime($value)->format('Y-m-d H:i:s');
219+
$value = $this->asDateTime($value)->format($this->getDateFormat());
210220
}
211221
}
212222

tests/ModelTest.php

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -318,7 +318,8 @@ public function testUnset()
318318

319319
public function testDates()
320320
{
321-
$user = User::create(array('name' => 'John Doe', 'birthday' => new DateTime('1980/1/1')));
321+
$birthday = new DateTime('1980/1/1');
322+
$user = User::create(array('name' => 'John Doe', 'birthday' => $birthday));
322323
$this->assertInstanceOf('Carbon\Carbon', $user->birthday);
323324

324325
$check = User::find($user->_id);
@@ -327,6 +328,16 @@ public function testDates()
327328

328329
$user = User::where('birthday', '>', new DateTime('1975/1/1'))->first();
329330
$this->assertEquals('John Doe', $user->name);
331+
332+
// test custom date format for json output
333+
$json = $user->toArray();
334+
$this->assertEquals($user->birthday->format('U'), $json['birthday']);
335+
$this->assertEquals($user->created_at->format('U'), $json['created_at']);
336+
337+
// test default date format for json output
338+
$item = Item::create(array('name' => 'sword'));
339+
$json = $item->toArray();
340+
$this->assertEquals($item->created_at->format('Y-m-d H:i:s'), $json['created_at']);
330341
}
331342

332343
public function testIdAttribute()

tests/models/User.php

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -84,4 +84,9 @@ public function getReminderEmail()
8484
{
8585
return $this->email;
8686
}
87+
88+
protected function getDateFormat()
89+
{
90+
return 'U';
91+
}
8792
}

0 commit comments

Comments
 (0)