Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

formatDateTime处理'datetime_format' => '\\app\\common\\util\\ModelDateTime'的问题 #603

Open
uniquekey-coder opened this issue Aug 8, 2024 · 0 comments

Comments

@uniquekey-coder
Copy link

uniquekey-coder commented Aug 8, 2024

    /**
     * 时间日期字段格式化处理.
     *
     * @param mixed $format    日期格式
     * @param mixed $time      时间日期表达式
     * @param bool  $timestamp 时间表达式是否为时间戳
     *
     * @return mixed
     */
    protected function formatDateTime($format, $time = 'now', bool $timestamp = false)
    {
        if (empty($time)) {
            return $time;
        }

        if (false === $format) {
            return $time;
        } elseif (str_contains($format, '\\')) {
            //如果$format传递的是类,这里返回的是类实例化的对象?是否应该是 return (string)new $format($time);调用__toString()方法
            return new $format($time);
        }

        if ($time instanceof DateTimeInterface) {
            $dateTime = $time;
        } elseif ($timestamp) {
            $dateTime = new DateTime();
            $dateTime->setTimestamp(is_numeric($time) ? (int) $time : strtotime($time));
        } else {
            $dateTime = new DateTime($time);
        }

        return $dateTime->format($format);
    }

这里的代码是不是有问题,在数据库配置中, 'datetime_format' => '\app\common\util\ModelDateTime',我传递的类,最终返回的是一个对象。这应该是一个历史遗留问题,在thinkphp view视图中,使用的是 echo $object,会自动调用__toString(),但如果不是在view中,就不会调用__toString()了,所以 return new $format($time) 会得到结果 “{}”

           if (false === $format) {
            return $time;
        } elseif (str_contains($format, '\\')) {
            //如果$format传递的是类,这里返回的是类实例化的对象?是否应该是 return (string)new $format($time);调用__toString()方法
            return new $format($time);
        }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant