Home » Php » php – laravel-4 how to change date format

php – laravel-4 how to change date format

Posted by: admin July 12, 2020 Leave a comment

Questions:

I want to insert a date into the clients table my db schema is below, I want to insert them into the start_day and end_day fields.

I have the below in validations in ClientController.php

If I insert a foreign date_format other than the one defined below I am thrown an error, but if I do insert the correct one it reverts to 0000-00-00. But if I change the field type to text for example the date_format is inserted fine.

$rules = array(
        'project_name'       => 'required',
        'project_brief'      => 'required',
        'start_day' =>  array('required', 'date_format:"m-d-Y"'),
        'end_day'   => array('required', 'date_format:"m-d-Y"')
    );

I’m not sure where the problem lies to be honest. I’ve even tried to convert the time doing the below:

$start_day_old = Input::get('start_day');
$start_day = date("d-m-Y", strtotime($start_day_old));
$project = new Project;
$project->start_day = $start_day
$project->save();

However the results were the same. Does anyone know how I can rectify this issue?

Clients DB Schema

How to&Answers:

You can’t insert a date formated as dd-mm-yyyy in mysql‘s date field, it should be yyyy-mm-dd, so in your code here

$start_day = date("d-m-Y", strtotime($start_day_old));

Change it to

$start_day = date("Y-m-d", strtotime($start_day_old));

So, if a date is 15-10-2010 then it’ll become 2010-10-15 and it’s a valid date for date field in the mysql database.