Can't save date from datepicker in mysql


#1

Hello to all the community…

I am new to cakephp and i have the following problem!

In my app a have a date input field witch takes date from jquery datepicker.The date format from date picker is dd-mm-yyyy but when i press the submit button it cant be saved to database date field and i recieve in database a value of 0000-00-00.

How can i convert the submited value to yyy-mm-dd format before it is saved to db?

Thanks very much…


#2

Hi,

Have you try, in your table file

public function beforeMarshal(Event $event, ArrayObject $data, ArrayObject $options)
{ 
      if (isset($data['myStringDate'])) {
        $data['myStringDate']) = (new Time($data['myStringDate']), 'America/Toronto'))->setTimezone('UTC');
    }
}

That should works. And do not forget to put on the top of your table file

use Cake\Event\Event;
use ArrayObject;

Hope it helps ! :wink:


#3

I think its better set cake configuration for your locale format so cake handles automatically the format conversion from/to database/print in all date / decimal type fields.

in app.php

'defaultLocale' => env('APP_DEFAULT_LOCALE', 'YOUR_LOCALE'),
'defaultTimezone' => env('APP_DEFAULT_TIMEZONE', 'YOUR_TIME_ZONE'),

in bootstrap.php:

Type::build('date')->useLocaleParser()->setLocaleFormat('dd-MM-yyyy');
Type::build('datetime')->useLocaleParser()->setLocaleFormat('dd-MM-yyyy HH:mm');
Type::build('timestamp')->useLocaleParser()->setLocaleFormat('dd-MM-yyyy HH:mm');
Type::build('decimal')->useLocaleParser();
Type::build('float')->useLocaleParser();
Time::setToStringFormat('dd-MM-yyyy HH:mm');
Date::setToStringFormat('dd-MM-yyyy');
FrozenTime::setToStringFormat('dd-MM-yyyy HH:mm');
FrozenDate::setToStringFormat('dd-MM-yyyy');

#4

Thank you very much for your answers…Finally Diego’s solution worked better for me!

Thank you both!!