Laravel Timestamp Format / JavaScript Date

I looked around, but could not find a clear way to return Laravel / datetimes timestamps in a specific format. It doesn't matter to me how it is stored in the database, but when I take the data, I would like to format it so that it can be parsed using JavaScript. Does anyone know a good way that does not require the creation of several accessories?

Edit: To add more details, I actually use AngularJS and would like the date returned in a format so that it can be understood using Angular and a date filter. In the current format, the date filter does not work, because it cannot parse the date from what I can say.

+4
source share
3 answers

To define an accessor, create a method in your model getFooAttributewhere Foo is the name of the cropped name of the camel that you want to get. Thus, you must define an accessor for the attribute test_date(or something else). The accessor is automatically called by Eloquent when trying to get the value test_date.

(In the example, I define it in the user model)

<?php

namespace App;

use Carbon\Carbon;

class User extends Model {
    protected $table = 'users';

    public function getTestDateAttribute($date) {
        //What format do you store in db?
        $storedformat = createFromFormat('Y-m-d H:i:s', $date);
        //What format would you like to show?
        $customformat = $storedformat->format('Y.m.d. H:i:s');
        return $customformat;
    }
}

Then by default you will see the following format:

$user = User::find(1);
$user->test_date; //2015.11.12. 8:50:20


If you want to write simpler code, you should use Traits .

Define the DateTrait file in the file App\DateTrait.php:

<?php

trait DateTrait {
    public function getTestDateAttribute($date) {
        //What format do you store in db?
         $storedformat = createFromFormat('Y-m-d H:i:s', $date);
         //What format would you like to show?
         $customformat = $storedformat->format('Y.m.d. H:i:s');
         return $customformat;
    }
 }

, test_date.

<?php

namespace App;

use Carbon\Carbon;

class User extends Model {
    use App\DateTrait;
...
}
0

- :

$variable->created_at->format('m-d-y')
+1

Carbon , .

, Javascript, , - - , , - :

{{ (new Carbon\Carbon($dataPassedIn->created_at))->format('F d, Y H:ia') }}

, September 02, 2015 09:43am, , javascript.

0

Source: https://habr.com/ru/post/1615527/


All Articles