php 如何从字符串强制转换为DateTimeInterface??Symfony AJAX

xytpbqjk  于 2023-02-11  发布在  PHP
关注(0)|答案(1)|浏览(118)

我真实的的问题是,我正在向我的API发送 AJAX Jquery请求,服务器响应是"::setDate()的参数#1必须是DateTimeInterface,给定字符串“
我试着投了,但没用。
我在JQUERY的 AJAX :

$.ajax({
            type: "PUT",
            url: "/api/distribucion",
            data: JSON.stringify(dist),
            dataType: "json",
            success: function (response) {
                console.log("mesa " + response.id + " actualizada");
            }
        });

我的PHP API(Symfony的控制器):

public function putDistribucion(ManagerRegistry $mr, Request $request): Response
    {
        $datos = json_decode($request->getContent());
        $datos = $datos->distribucion;
        // Cogemos el ID de el Distribucion a editar
        $id = $datos->id;
        // Obtenemos el Distribucion
        $distribucion = $mr->getRepository(Distribucion::class)->find($id);
        // Cambiamos todos sus campos
        $distribucion->setPosicionX($datos->pos_x);
        $distribucion->setPosicionY($datos->pos_y);
        $distribucion->setFecha($datos->fecha);
        $distribucion->setMesaId($datos->mesa_id);
        $distribucion->setAlias($datos->alias);
        $distribucion->setReservada($datos->reservada);

        $manager = $mr->getManager();
        try {
            // Lo mandamos a actualizar
            $manager->persist($distribucion);
            $manager->flush();
        } catch (PDOException $e) {
            $this->json(['message' => $e->getMessage(), "Success" => false], 400);
        }

        # Creado con éxito => Devolvemos la ID
        return $this->json(
            [
                "message" => "Éxito al editar la distribucion " . $id,
                "Success" => true
            ],
            202 // Aceptado
        );
    }

我要发送的对象:

jtw3ybtb

jtw3ybtb1#

您的实体Distribucion可能有一个如下所示的setter:

public function setFecha(DateTimeInterface $fecha): self
    {
        $this->fecha = $fecha;

        return $this;
    }

setter使用DateTimeInterface进行类型提示,因此需要使用DateTime对象而不是字符串。
您可以使用DateTime::createFromFormat轻松创建DateTime
因此$distribucion->setFecha($datos->fecha);将变成如下形式:

$distribucion->setFecha(DateTime::createFromFormat('YYYY-MM-DD HH:ii:ss.u', $datos->fecha));

您可能需要验证我用作DateTime::createFromFormat的第一个参数的日期格式
公共静态DateTime::createFromFormat(字符串$格式,字符串$日期时间,?DateTimeZone $时区=空)

相关问题