Reputation: 2306
i have a problem about the correct timezone when patching an entity. My post request looks like this:
[
'event_date' => '11.07.2019',
'start_time' => '15:00',
'end_time' => '16:00'
]
In my form I have a calendar and two fields where the user can choose the start and end time. Now these values are the timezone of the user. What I want is to convert those values to UTC and save them with my entity which has two DATETIME
and one DATE
fields.
To save it correctly without any validation error I have the following code for modifying the data before patching:
$event_date = new \DateTime($data['event_date']);
$start_time = new \DateTime($data['start_time']);
$end_time = new \DateTime($data['end_time']);
$start_time->setDate($event_date->format('Y'), $event_date->format('m'), $event_date->format('d'));
$end_time->setDate($event_date->format('Y'), $event_date->format('m'), $event_date->format('d'));
$data['start_time'] = $start_time;
$data['end_time'] = $end_time;
$data['event_date'] = $event_date;
But as you can see from the debug it converts it wrong. Cause I'm in the europe timezone it should have 2 hours less.
[
'event_date' => object(DateTime) {
date => '2019-07-11 00:00:00.000000'
timezone_type => (int) 3
timezone => 'UTC'
},
'start_time' => object(DateTime) {
date => '2019-07-11 15:00:00.000000'
timezone_type => (int) 3
timezone => 'UTC'
},
'end_time' => object(DateTime) {
date => '2019-07-11 16:00:00.000000'
timezone_type => (int) 3
timezone => 'UTC'
}
]
I configured my bootstrap like this:
Time::setToStringFormat('d.m.Y H:i');
Time::setJsonEncodeFormat('d.m.Y H:i');
FrozenTime::setToStringFormat('d.m.Y H:i');
FrozenTime::setJsonEncodeFormat('d.m.Y H:i');
Date::setToStringFormat('d.m.Y');
Date::setJsonEncodeFormat('d.m.Y');
FrozenDate::setToStringFormat('d.m.Y');
FrozenDate::setJsonEncodeFormat('d.m.Y');
Type::build('time')
->useImmutable();
Type::build('date')
->useImmutable();
Type::build('datetime')
// ->useImmutable()
->useLocaleParser()
->setLocaleFormat('d.m.Y H:i:ss');
Can someone help me here? I'm a bit confused...
Upvotes: 1
Views: 884
Reputation: 25698
Well, you're not using the Date and DateTime objects from Cake at all: \DateTime
this mean it is the plain php DateTime object.
Fix that and use the correct objects and see what happens then. Also make sure you configured your default time zone correctly. Have a read: https://book.cakephp.org/3.0/en/core-libraries/time.html
Upvotes: 1