在我的symfony应用程序中,我有一个日期时间的变量,如实体级别所示
/**
* @var \DateTime
*
* @ORM\Column(name="time", type="datetime", nullable=true)
*/
private $time;
我正在检查控制器中的时间,如图所示
$data = array();
foreach ($Messages as $Message)
{
array_push($data, $this->serialize($Message));
}
$response = new Response(json_encode($data), 200);
这是序列化方法
private function serialize(Message $Message) {
return array(
'message' => $Message->getMessage(),
'regfk' => $Message->getRegistrationfk(),
'carefk' => $Message->getCarefk(),
'time' => $Message->getMessagedate(),
'usertype' => $Message->getUsertype(),
);
}
在回复中,我正在以格式获取时间,
"time":{"date":"2017-06-08 00:03:02","timezone_type":3,"timezone":"Europe\/Paris"}
请问我怎样才能从datetime变量中获取时间
答案 0 :(得分:1)
尝试:
private function serialize(Message $Message) {
return array(
'message' => $Message->getMessage(),
'regfk' => $Message->getRegistrationfk(),
'carefk' => $Message->getCarefk(),
'time' => $Message->getMessagedate()->format('H:i:s'),
'usertype' => $Message->getUsertype(),
);
}
如果您无法确定getMessagedate()
总是返回\DateTime
对象,则需要添加空检查:
'time' => $Message->getMEssagedate() != null ? $Message->getMessagedate()->format('H:i:s') : '',
答案 1 :(得分:1)
如果你这样做,你推送一个正常的响应给你的DateTime对象:
private function serialize(Message $Message) {
return array(
'message' => $Message->getMessage(),
'regfk' => $Message->getRegistrationfk(),
'carefk' => $Message->getCarefk(),
'time' => $Message->getMessagedate()->format('G:i'),
'usertype' => $Message->getUsertype(),
);
}
应该很好用
答案 2 :(得分:0)
您可以在此处使用时间类型
/**
* @Assert \Time()
*
*/
private $time;
http://symfony.com/doc/current/reference/constraints/Time.html