如何从symfony2 / php中的字符串创建DateTime对象 [英] How to create DateTime object from string in symfony2/php

查看:74
本文介绍了如何从symfony2 / php中的字符串创建DateTime对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在一个数据库表中,我有几个字段以 datetime 作为字段类型。因此,我只需要将数据保留为日期时间对象。

In a DB table I have several fields with datetime as field type. So I need to persist data only as date time object.

从表单中,我将日期时间作为字符串获取,例如

From a form I get date time as string like

2012-10-05 17:45:54

现在,无论何时我坚持我的实体,我都会得到以下错误:

Now when ever I persist my entity I get following error:


致命错误:在非对象上调用成员函数format()在
..\DateTimeType.php在第44行

Fatal error: Call to a member function format() on a non-object in ..\DateTimeType.php on line 44

我尝试过

$protocol->setStartedAt(strtotime($post['started_at']));

$from = \DateTime::createFromFormat('yy-mm-dd hh:mm:ss', $post['started_at']);
$protocol->setStartedAt($from);

或者只是

$from = new \DateTime($post['started_at']);
$protocol->setStartedAt($from);

最后一个代码有效,但是它不使用传递的时间戳作为争论,而只是获取当前时间。

The last code works but it does not uses the timestamp passed as arguement but just gets the current time.

有什么想法吗?

推荐答案

我总是用其创建DateTime对象构造函数,在您的情况下,操作系统应该是:

i always create DateTime object with its constructor, os in your case it would be:

$protocol->setStartedAt(new \DateTime($post['started_at']));

如果这可行,但不使用发布的时间戳,则您可能没有$ post中的值['started_at']。尝试对其进行调试,或者只是做一些卑鄙的把戏:

if this works, but does not use the timestamp posted you probably do not have the value in $post['started_at']. Try debuging it or just do the dirty trick:

die($post['started_at']);

这篇关于如何从symfony2 / php中的字符串创建DateTime对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆