user3845661
user3845661

Reputation:

Time format of database field, help needed

Time is stored in my database as H:i:s format for a timefield. When I query I want time returned as hours:minutes without the seconds part.

I tried to set the "protected $dateFormat " setting using a Mutator. Can anyone show an example of the dateFormat setting needed? The database must remain hour:minute:seconds time settings, only the retrieved value needs to be changed for display.

protected $dateFormat = 'Y-m-d H:i:s'; // ?

Upvotes: 0

Views: 65

Answers (3)

user3845661
user3845661

Reputation:

// converting db column name time_match into the function as getTimeMatchAttribute worked for me. 

public function getTimeMatchAttribute($value){
        return date('H:i',strtotime($value));
    }

Upvotes: 1

Vinícius Alonso
Vinícius Alonso

Reputation: 151

One way to solve it is to treat dates as Carbon instances. The format to save on database will be auto-converted and you should use in any format.

protected $dates = [
    'field_name'
];

https://laravel.com/docs/5.8/eloquent-mutators#date-mutators

Upvotes: 1

Mohammed Aktaa
Mohammed Aktaa

Reputation: 1353

you can make it with getters function in your model like this:

public function getTimeAttribute($time){
   return date('h:i',strtotime($time))
 }

Time in function name should be your column name in upper case

Upvotes: 0

Related Questions