php 字符串到 DateTime 对象

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

String to DateTime Object

phpstringdatetime

提问by MAB

I'm new at String functions, so I need a complex substr and trim functions for this string:

我是字符串函数的新手,所以我需要一个复杂的 substr 和 trim 函数来处理这个字符串:

Wed, 28 Dec 2011 13:04:30 GMT

String comes to me always with this format. I want to convert it to DateTime object. Anybody can help me?

字符串总是以这种格式出现在我面前。我想将它转换为 DateTime 对象。任何人都可以帮助我吗?

回答by Mark Baker

$dateString = 'Wed, 28 Dec 2011 13:04:30 GMT';
$dateTime = datetime::createfromformat('D, d M Y H:i:s e',$dateString);

echo $dateTime->format('d-M-Y H:i:s e');

回答by álvaro González

<?php
$date = new DateTime('Wed, 28 Dec 2011 13:04:30 GMT');
echo $date->format('r');

... prints:

... 印刷:

Wed, 28 Dec 2011 13:04:30 +0000

回答by Robert Saylor

If you are wanting to take a date string and write that to the database as a date object using Doctrine:

如果您想获取日期字符串并使用 Doctrine 将其作为日期对象写入数据库:

Note: This is a form post example for Symfony 3 and 4.

注意:这是 Symfony 3 和 4 的表单发布示例。

$mynewdateobject = new \DateTime($request->request->get('mydatestring'));

Then you can write the object to the database or use it elsewhere in your code.

然后您可以将对象写入数据库或在代码中的其他地方使用它。