PHP:数组中的 DATETIME 作为对象。如何回声

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4016727/
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 11:44:32  来源:igfitidea点击:

PHP: DATETIME in array as object. How to echo

phparraysdatetimeobject

提问by iamjonesy

Hope that title isn't too cryptic. I have an array with a DATETIME object in it and I'm just trying to figure out how to echo this to a page.

希望这个标题不要太神秘。我有一个包含 DATETIME 对象的数组,我只是想弄清楚如何将其回显到页面。

 ["created"]=> object(DateTime)#3 (3) { ["date"]=> string(19) "2010-10-22 00:00:00" ["timezone_type"]=> int(3) ["timezone"]=> string(13) "Europe/London"

Can someone help me out?

有人可以帮我吗?

tried date() but get:

尝试过 date() 但得到:

Warning: date() expects parameter 2 to be long, object given in C:\

any help most appreciated,

最感谢的任何帮助,

Jonesy

琼斯

采纳答案by Evan Mulawski

回答by Pekka

Use DateTime::format(). The mask syntax is identical to date()'s.

使用DateTime::format(). 掩码语法与date()'s相同。

echo $value->format('Y-m-d H:i:s');

回答by Kamafeather

I add this answer even if I am not sure it answers specifically the question (and best answer is already there though), but I couldn't find much other places where the above format (date/timezone_type/timezone) is mentioned.

我想补充,即使我不是这个答案肯定它明确回答了这个问题(和最好的答案是已经在那里虽然),但我找不到地方上面的格式(很多其他地方date/ timezone_type/timezone被提及)。

If you have the date translated from object to array

如果您将日期从对象转换为数组

  • via var_export
  • 通过 var_export

DateTime::__set_state(array( 'date' => '2017-12-05 11:58:25.428595', 'timezone_type' => 3, 'timezone' => 'US/Pacific', ))

DateTime::__set_state(array( 'date' => '2017-12-05 11:58:25.428595', 'timezone_type' => 3, 'timezone' => 'US/Pacific', ))

  • or json_encode
  • 或者 json_encode

{"date":"2017-12-05 11:57:07.938671","timezone_type":3,"timezone":"US\/Pacific"}

{"date":"2017-12-05 11:57:07.938671","timezone_type":3,"timezone":"US\/Pacific"}

you can use again the DateTime::__set_statemagic method mentioned above to convert it again to a DateTimeobject.

您可以再次使用上述DateTime::__set_state魔术方法将其再次转换为DateTime对象

Not sure how here __set_statecould bidirectional, but it does the magic. I couldn't find documentation.

不知道这里是如何__set_state双向的,但它确实神奇。我找不到文档。

But you can test it here: http://sandbox.onlinephpfunctions.com/code/0a18e6937e7d4373beb91713f2e6e5f75f9af3e2

但你可以在这里测试:http: //sandbox.onlinephpfunctions.com/code/0a18e6937e7d4373beb91713f2e6e5f75f9af3e2

回答by Dave

If it's an actual php5 DateTimeobject then you can use the formatmethod to echo it

如果它是一个实际的 php5 DateTime对象,那么您可以使用该format方法来回显它

$myDate = $myArray['created'];
echo $myDate->format('Y-m-d H:i:s');