CodeIgniter Forums
Best practice for date in entity - Printable Version

+- CodeIgniter Forums (https://forum.codeigniter.com)
+-- Forum: CodeIgniter 4 (https://forum.codeigniter.com/forumdisplay.php?fid=28)
+--- Forum: CodeIgniter 4 Support (https://forum.codeigniter.com/forumdisplay.php?fid=30)
+--- Thread: Best practice for date in entity (/showthread.php?tid=77732)



Best practice for date in entity - paul - 10-12-2020

hello

in a form i have a date in format 'dd/mm/yyyy'

i use entity and i want save the date in sql with model

i do in my model
Code:
$myEntity = new TheEntity($data);
        if ($this->save($myEntity))

this send me an error

DateTime::__construct(): Failed to parse time string (19/03/2016) at position 0 (1): Unexpected character


i have create a setter in my entity
Code:
protected $dates = ['date_naissance'];
   
    public function setDateNaissance($date)
    {
        if (empty($date)) {
            $this->attributes['date_naissance'] = null;
            return $this;
        }else{
            $this->attributes['date_naissance'] = date('Y-m-d', strtotime(str_replace('/', '-', $date)));
            return $this;
        }
    }
but the setter isn't call before the error


RE: Best practice for date in entity - InsiteFX - 10-12-2020

The date is saved as an integer your trying to pass illegal characters into it remove all / -
20201012


RE: Best practice for date in entity - tmtuan - 10-12-2020

in CI4 they have the Time class, try to use this

use CodeIgniter\I18n\Time;

then you can format the form date to mysql datetime before save it to DB