如何从 symfony2/php 中的字符串创建 DateTime 对象

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12750050/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 04:08:55  来源:igfitidea点击:

How to create DateTime object from string in symfony2/php

phpdatetimesymfony

提问by Upvote

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

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

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:

现在,当我坚持我的实体时,我会收到以下错误:

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

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

I tried with

我试过

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

or

或者

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

or just

要不就

$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.

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

Any ideas?

有任何想法吗?

回答by Laurynas Mali?auskas

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

我总是用它的构造函数创建 DateTime 对象,在你的情况下它是:

$protocol->setStartedAt(new \DateTime($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:

如果这有效,但不使用发布的时间戳,则您可能没有 $post['started_at'] 中的值。尝试调试它或只是做肮脏的把戏:

die($post['started_at']);

回答by briosheje

For the sake of future readers who surelywill someday encounter this problem (this is the first post if you google "symfony 2 datetime from string"), keep in mind that in Symfony 2 the DateTime object does NOT accept a string with that format : "d/m/Y H:i:s", and probably doesn't support many others either.

为了将来肯定会遇到这个问题的读者(如果你用谷歌搜索“symfony 2 datetime from string”,这是第一篇文章),请记住,在 Symfony 2 中,DateTime 对象不接受具有该格式的字符串:"d/m/Y H:i:s",并且可能也不支持许多其他人。

For the sake of not becoming madat that, I've actually found out that the easiest and safest solution to avoid such errors is this one:

为了不生气,我实际上发现避免此类错误的最简单和最安全的解决方案是:

First, get your date stringfrom whatever kind of request you are doing (In my case a generic AJAX request) and convert it to a DateTime Object, this example assumes that we need to create a dateTime object for 25/04/2015 15:00, which is the format of the jQuery UI italian DateTimePicker (that's just an example):

首先,从您正在执行的任何类型的请求中获取您的日期字符串(在我的情况下是一个通用的 AJAX 请求)并将其转换为DateTime Object,此示例假设我们需要为 创build一个 dateTime 对象25/04/2015 15:00,这是jQuery UI 意大利语 DateTimePicker(这只是一个例子):

$literalTime    =   \DateTime::createFromFormat("d/m/Y H:i","25/04/2015 15:00");

(note: use \to use php's DateTime object, else you will be using Symfony's datetime object that will throw you an exception)

(注意:用于\使用 php 的 DateTime 对象,否则您将使用 Symfony 的 datetime 对象,它会抛出异常)

Then, once you did it, create a date stringusing the comfort formatfunction, by giving to the first parameter the output format expected (Y-m-d H:i:s):

然后,完成后,使用comfort format函数创建一个日期字符串,通过为第一个参数提供预期的输出格式():Y-m-d H:i:s

$expire_date =  $literalTime->format("Y-m-d H:i:s");

In this way you are 100% sure that whatever kind of format you are passing or receiving this will properly be converted and you won't get any kind of exception from the DateTime symfony object, as long as you provide what you are expecting as an input.

通过这种方式,您可以 100% 确定您传递或接收的任何类型的格式都将被正确转换,并且您不会从 DateTime symfony 对象中获得任何类型的异常,只要您提供您所期望的作为输入

Knowing that this post is actually quite old, I've just decided to post that because I didn't find any other valuable source but this one to understand where the problem could have been.

知道这篇文章实际上已经很旧了,我只是决定发布它,因为我没有找到任何其他有价值的来源,除了这个可以了解问题可能出在哪里。

Please note that the best solution is still to send the datetime string in the correct format already, but if you literally have no ways to do that the safest way to convert such a string is the one above.

请注意,最好的解决方案仍然是以正确的格式发送日期时间字符串,但如果您确实没有办法这样做,那么转换此类字符串的最安全方法是上面的方法。

回答by watermanio

How about createFromFormat?

createFromFormat 怎么样?

http://uk.php.net/manual/en/datetime.createfromformat.php

http://uk.php.net/manual/en/datetime.createfromformat.php

$from = DateTime::createFromFormat($post['started_at'], 'Y-m-d H:i:s');