Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Storing time strings to TIME column in Laravel

I use a timepicker to get a time string(eg: '1:00am' or '12:00pm'). I need to modify and store this in a mysql TIME data type column as eg: '12:00:00'. Now, since the TIME column stores in 24 hrs format, I need to "modify" it. I can't seem to find any help to modify using Carbon, since I'm not using any dates. I'm using a mutator in Laravel, but would like to know if there is a better way like using Carbon for dates.

public function setTimeAttribute($time) {
    if(substr($time, -2, 0) == 'am') {
        // do nothing
    } else if(substr($time, -2, 0) == 'pm') {
        // increase hours.ie: 1:00pm to 13:00:00
    }
 }

Any help would be appreciated! Thanks.

like image 958
donnyjeremiah Avatar asked Jul 23 '16 08:07

donnyjeremiah


1 Answers

Use PHP strtotime() function.

$time = "12:00am";

$timestamp = strtotime($time);

echo $timestamp;

//Will print something like: 1469228400

Or any other date format you prefer.

It's best to store time as timestamp, to convert it back you can use date() function. E.g: $value = date("H:i:s", $timestamp);

like image 53
Michel Avatar answered Oct 18 '22 22:10

Michel