Welcome Guest, Not a member yet? Register   Sign In
Cast datetime from JSON string?
#1

I have discovered a new behavior for Datetime Cast https://github.com/codeigniter4/CodeIgni...meCast.php It can only recover from a string or a number. But for the API, the JSON result has an array
PHP Code:
array(3) {
  ["date"]=>
  string(26"2023-11-25 10:20:35.000000"
  ["timezone_type"]=>
  int(3)
  ["timezone"]=>
  string(13"Europe/Moscow"


Do you have any ideas how to do this better? Just taking the date may be wrong, the time zone will be lost
Reply
#2

See https://github.com/codeigniter4/CodeIgniter4/pull/8230
Reply
#3

No, in PR DatetimeCast apply only string value.
But Json have array: created_at => [ date, timezone, timezone_type]
Not simple "date* string
Reply
#4

You need to write a custom cast handler for it.

By the way, why is your date in JSON strange format like that?
Reply
#5

Hmm, its default DatetimeCast converter.


PHP Code:
    // Project entity
    protected $casts  = [
        'id'        => 'int',
        'user_id'    => 'int',
        'name'      => 'string',
        'link'      => 'string',
        'archival'  => 'string',
        'created_at' => 'datetime',
    ];

// Controller send response
return $this->response->setJSON($project);

// Get response after CURLRequest
    {
        "id"1,
        "user_id"1,
        "name""Project #1",
        "link""https://ya.ru",
        "archival""no",
        "created_at": {
            "date""2023-11-25 10:20:35.000000",
            "timezone_type"3,
            "timezone""Europe/Moscow"
        }
    
Reply
#6

Isn't it a bug?

If you need datetime with timezone, it is better to use string with timezone like "2005-08-15T15:52:01+00:00".
https://www.php.net/manual/en/class.date...ants.types
Reply
#7

This is the behavior of the built-in DatetimeCast. It's not particularly critical for me, I added a new ExtDatetimeCast
Perhaps it is worth adding a special exception for dates in the Entity? toArray() executes castAs() and therefore the JSON gets not a string, but an object
PHP Code:
    /**
    * Support for json_encode()
    *
    * @return array
    */
    #[ReturnTypeWillChange]
    public function jsonSerialize()
    {
        return $this->toArray();
    
Reply
#8

The current Entity is somewhat broken.
I don't know what toArray() is.
Reply
#9

Return all casted properties, and not just strings

https://github.com/codeigniter4/CodeIgni...y.php#L166
Reply
#10

In my opinion, casts in Entity is broken.
and toRawArray() does not return raw value (string) if it is Time object.
Reply




Theme © iAndrew 2016 - Forum software by © MyBB