I am writing an app which get data from Strava API.
When create new Entity, it does not allow getting date time from returned text.
My field is Date Time type, and the returned value from API is:
"start_date": "2023-04-15T10:49:06Z",
"start_date_local": "2023-04-15T17:49:06Z",
I really dont know that type of that string is.
Can anyone help me patch that value into my DateTime field in Entity?
Thank you so much.
Zuluru
March 14, 2024, 6:13pm
2
That’s the ISO standard format for dates. I’d think that it would be handled directly by the patch process, if it knows that start_date
is a date time field.
As for start_date_local
, that seems less useful. You should be storing all dates in UTC in your database, and generate local time for the current user on demand based on some profile preference.
Thank you Zuluru,
However, the Entity does not know how to patch that fields.
In database, the field is datetime , in CakePHP, the table defines the filed as datetime too, with validator as below:
$validator
->dateTime('start_date')
->notEmptyDateTime('start_date');
However, when patching, there is error, and the error message is as below:
'dateTime' => 'The provided value must be a date and time of one of these formats: `ymd`',
I also made a test newEntity with different datetime string format as below, it works
$testData = array();
$testData['name'] = 'test act';
$testData['user_id'] = '3';
$testData['elapsed_time'] = 600;
$testData['start_date'] = '2023-04-15 10:49:06';
$testData['start_date_local'] = '2023-04-15 17:49:06';
$testAct = $activityTable->newEntity($testData);
I think that the little different in datetime string format causing this.
'2023-04-15 10:49:06'
vs
"2023-04-15T10:49:06Z"
I am using CakePHP 5.0.5, if that is relevant.
Thanks Zuluru but it does not work.
I have to manipulate data manually to get rid of the “T” and “Z” in the datetime string before patching entity.
jmcd73
March 17, 2024, 11:32pm
6
When ingesting those dates can you use DateTimeImmutable or Chronos?
$table = $this->fetchTable('Strava');
// Chronos::ATOM = 'Y-m-d\\TH:i:sP';
$strava = $table->newEntity([
'date_1' => Chronos::createFromFormat(
format: Chronos::ATOM,
time: "2023-04-15T10:49:06Z"
),
'date_2' => Chronos::createFromFormat(
Chronos::ATOM,
"2023-04-15T17:49:06Z"
),
]);
dd($strava);
Output
########## DEBUG ##########
object(App\Model\Entity\Strava) id:0 {
'date_1' => object(Cake\Chronos\Chronos) id:1 {
'hasFixedNow' => false
'time' => '2023-04-15 10:49:06.000000'
'timezone' => 'UTC'
}
'date_2' => object(Cake\Chronos\Chronos) id:2 {
'hasFixedNow' => false
'time' => '2023-04-15 17:49:06.000000'
'timezone' => 'UTC'
}
'[new]' => true
'[accessible]' => [
'date_1' => true,
'date_2' => true
]
'[dirty]' => [
'date_1' => true,
'date_2' => true
]
'[original]' => []
'[originalFields]' => [
(int) 0 => 'date_1',
(int) 1 => 'date_2'
]
'[virtual]' => []
'[hasErrors]' => false
'[errors]' => []
'[invalid]' => []
'[repository]' => 'Strava'
}
###########################