46

I am new in Laravel. I am creating a application with laravel. When i creating a post then the values of "created_at" and 'updated_at" are look like this:

2014-06-26 04:07:31
2014-06-26 04:07:31

But i want this values without time look like this :

2014-06-26
2014-06-26

Only date without time.

Is it possible ???

Please help me.

My Post Model:

<?php

class Post extends \Eloquent {

    protected $fillable = array('title', 'body', 'meta','reporter', 'slug', 'image','top');

    public static $rules = array(
        'title'=>'required|min:2',
        'body'=>'required|min:20',
        'reporter'=> 'required|min:2',
        'image'=>'image|mimes:jpeg,jpg,bmp,png,gif'
    );

    public function categories()
    {
        return $this->belongsToMany('Category');
    }

}

My Post Controller store:

public function store()
{
    $validator = Validator::make(Input::all(), Post::$rules);

    if ($validator->passes()) {
        $post = new Post;
        $post->title = Input::get('title');
        $post->body = Input::get('body');
        $post->reporter = Input::get('reporter');
        $post->meta = Input::get('meta');
        $post->slug = Input::get('title');
        $post->top = Input::get('top');

        $image = Input::file('image');
        if ($image) {
            $filename = date('Y-m-d-H:i:s')."-".$image->getClientOriginalName();
            Image::make($image->getRealPath())->resize(250, 145)->save('public/images/postimages/'.$filename);
            $post->image = 'images/postimages/'.$filename;
        }


        $categories = Input::get('categories');

        $post->save();

        $post->categories()->sync($categories);

        return Redirect::route('admin.posts.index')
            ->with('message', 'Product Created');
    }

    return Redirect::back()
        ->with('message', 'Something went wrong')
        ->withErrors($validator)
        ->withInput();
}

Please Help me.

saiful408
  • 501
  • 1
  • 4
  • 9

13 Answers13

88

In your Post model add two accessor methods like this:

public function getCreatedAtAttribute($date)
{
    return Carbon\Carbon::createFromFormat('Y-m-d H:i:s', $date)->format('Y-m-d');
}

public function getUpdatedAtAttribute($date)
{
    return Carbon\Carbon::createFromFormat('Y-m-d H:i:s', $date)->format('Y-m-d');
}

Now every time you use these properties from your model to show a date these will be presented differently, just the date without the time, for example:

$post = Post::find(1);
echo $post->created_at; // only Y-m-d formatted date will be displayed

So you don't need to change the original type in the database. to change the type in your database you need to change it to Date from Timestamp and you need to do it from your migration (If your using at all) or directly into your database if you are not using migration. The timestamps() method adds these fields (using Migration) and to change these fields during the migration you need to remove the timestamps() method and use date() instead, for example:

$table->date('created_at');
$table->date('updated_at');
The Alpha
  • 143,660
  • 29
  • 287
  • 307
  • 2
    Working, but you shouldn't be changing the format inside your model. You should do it from inside your view : $post->created_at->format('Y-m-d'); You can also change the format globally for every dates by using the static method Carbon\Carbon::setToStringFormat('Y-m-d'); – arthur.flachs Jun 26 '14 at 23:18
  • 2
    `Laravel` provides a convenient way to do it from model instead of using it in every view, nothing is bad here but there are other ways, for example: using a `view presenter` class. – The Alpha Jun 26 '14 at 23:24
  • 1
    using `public static $dates = ['updated_at', 'created_at'];` in your model will make these fields `Carbon` by default, so inside your `getXXXAttribute()` methods you only type `return $this->updated_at->format('Y-m-d')` – Zanshin13 Dec 07 '15 at 12:24
  • Is is on a per-model basis. I wonder if there a global (configuration-based) approach? – Roland Jun 22 '18 at 12:57
  • It's per model basis but if you have a parent model than which extends eloquent model then you can do that easily. – The Alpha Jun 22 '18 at 16:29
77
{{ $post->created_at }}

will return '2014-06-26 04:07:31'

The solution is

{{ $post->created_at->format('Y-m-d') }}
Maged Hamid
  • 952
  • 1
  • 9
  • 18
  • Thanks. for providing one that works within Blade. Should've known an error wasn't thrown when using the property directly because of a __toString method. – Verron Knowles Dec 06 '14 at 21:04
  • This is formatting dates individually but the questioner asked for changing default format, not per individual blade usage. – Roland Jun 22 '18 at 12:52
13

Laravel 4.x and 5.0

To change the time in the database use: http://laravel.com/docs/4.2/eloquent#timestamps

Providing A Custom Timestamp Format

If you wish to customize the format of your timestamps, you may override the getDateFormat method in your model:

class User extends Eloquent {

    protected function getDateFormat()
    {
        return 'U';
    }

}

Laravel 5.1+

https://laravel.com/docs/5.1/eloquent

If you need to customize the format of your timestamps, set the $dateFormat property on your model. This property determines how date attributes are stored in the database, as well as their format when the model is serialized to an array or JSON:

class Flight extends Model
{
    /**
     * The storage format of the model's date columns.
     *
     * @var string
     */
    protected $dateFormat = 'U';
}
Loren
  • 9,783
  • 4
  • 39
  • 49
  • 1
    You can also just set `protected $dateFormat = 'U';` – Ben Harold Nov 15 '17 at 01:34
  • 1
    I think that only exists in newer editions of Laravel, but I'll update the answer to note that. – Loren Nov 15 '17 at 13:33
  • In Laravel 5.6 `$dateFormat` is public – Daniel May 02 '18 at 07:47
  • @Daniel It looks like it is still protected to me: https://github.com/illuminate/database/blob/5.6/Eloquent/Concerns/HasAttributes.php#L57 Can you point to where it is public? – Loren May 02 '18 at 12:46
  • @Loren https://laravel.com/docs/5.6/upgrade (`This getDateFormat method is now public instead of protected.`) – Daniel May 02 '18 at 15:53
  • @Daniel Ah, got it, `$dateFormat` (the field), however is still protected and is the easiest thing to override for Laravel 5.1+ to change the date format (rather than overriding the `getDateFormat` method). – Loren May 03 '18 at 13:08
9

You can also try like this.

Use Carbon\Carbon;


$created_at = "2014-06-26 04:07:31";

$date = Carbon::parse($created_at);

echo $date->format("Y-m-d");
primo
  • 1,340
  • 3
  • 12
  • 40
Amit Kumar
  • 249
  • 3
  • 10
8

You could use

protected $casts = [
    'created_at' => "datetime:Y-m-d\TH:iPZ",
];

in your model class or any format following this link https://www.php.net/manual/en/datetime.format.php

Timy Shark
  • 316
  • 3
  • 5
7

If anyone is looking for a simple solution in Laravel 5.3:

  1. Let default timestamps() be saved as is i.e. '2016-11-14 12:19:49'

  2. In your views, format the field as below (or as required):

     date('F d, Y', strtotime($list->created_at))
    
Zoe
  • 27,060
  • 21
  • 118
  • 148
nwaweru
  • 1,723
  • 1
  • 13
  • 14
2

Casting is the proper way to do this in Laravel 9+ and regardless of your front-end; blade, vue, react... the variables will be treated properly.

/**
 * The attributes that should be cast.
 *
 * @var array
 */
protected $casts = [
    'created_at' => 'datetime:Y-m-d',
    'updated_at' => 'datetime:Y-m-d',
    'json' => 'object',
    'active' => 'boolean',
];

https://laravel.com/docs/9.x/eloquent-mutators#date-casting

JonC
  • 21
  • 1
0

In laravel 6 the latest one can easily add in the "APP/user.php" model:

/**
 * The storage format of the model's date columns.
 *
 * @var string
 */
protected $dateFormat = 'U';

And in schema one can add

    $table->integer('created_at')->nullable();
    $table->integer('updated_at')->nullable();
MR_AMDEV
  • 1,712
  • 2
  • 21
  • 38
0

Use Carbon\Carbon;

$targetDate =  "2014-06-26 04:07:31";
Carbon::parse($targetDate)->format('Y-m-d');
Martin Brisiak
  • 3,872
  • 12
  • 37
  • 51
Hasibul Hasan
  • 53
  • 1
  • 3
0

For newers versions of laravel, you just need to declare it in your Model, like this:

class Your_class_name extends Model {

    protected $dateFormat = 'Y-m-d';

    ...


}
Yan Koshelev
  • 1,059
  • 1
  • 5
  • 10
0

The easiest way is just doing it directly in the blade file

$post->created_at->format('Y-m-d')
Mwaza
  • 1
  • 2
0

In laravel 8 to 10

When setting the

protected $timeStamps = 'Y-m-d H:i:s';

This only affects when you update or create

but when you get/fetch from an eloquent the format will always have a timestamp with timezone which is the default

sample:

2023-06-14T06:27:18.000000Z

// on your Model.php

use use DateTimeInterface;
protected function serializeDate(DateTimeInterface $date): string
{
    return $date->format('Y-m-d H:i:s');
}

Everytime you user Eloquent to query the timestamps if enabled will now have the Y-m-d H:i:s format

if you like it to be in effect to all model, Just create a BaseModel with the following property then Extend all your models

Read More at Laravel 10 - Date Casting

tomexsans
  • 4,454
  • 4
  • 33
  • 49
-1

LARAVEL 9^
in your model add this.

use Carbon\Carbon;

protected $dates = ['created_at','updated_at'];

protected function serializeDate(DateTimeInterface $dates)
{
    //return Carbon::createFromFormat('Y-m-d H:i:s', $dates)->diffForHumans();
    OR
    //return Carbon::createFromFormat('Y-m-d H:i:s', $dates)->format('Y-m-d');
}