File tree Expand file tree Collapse file tree 3 files changed +28
-2
lines changed Expand file tree Collapse file tree 3 files changed +28
-2
lines changed Original file line number Diff line number Diff 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
Original file line number Diff line number Diff 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 ()
Original file line number Diff line number Diff 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}
You can’t perform that action at this time.
0 commit comments