laravel PHP - 将字符串转换为日期
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/39738902/
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
PHP - Convert string to date in
提问by baig772
I am getting a string like Wed Sep 28 2016 01:00:00 GMT+0500 (PKT)and I need to convert it to 2016-09-28 01:00:00I have tried this
我得到一个像Wed Sep 28 2016 01:00:00 GMT+0500 (PKT)这样的字符串,我需要将它转换为2016-09-28 01:00:00我试过这个
$startTime = strtotime($updatedData['start']);
echo $time = date("Y-m-d H:i:s",$startTime);
but it returns me 2016-09-27 20:00:00
但它返回给我2016-09-27 20:00:00
回答by danopz
You could change it to use DateTime
:
您可以将其更改为使用DateTime
:
$startTime = new DateTime('Wed Sep 28 2016 01:00:00 GMT+0500 (PKT)');
echo $startTime->format('Y-m-d H:i:s');
DateTime keeps the timezone you give him.
DateTime 保留您给他的时区。
Live Example: https://3v4l.org/UTltO
现场示例:https: //3v4l.org/UTltO
回答by Jason Seah
@copynpaste solution is nice and straight forward but I will still share my solution by using Carbon.
@copynpaste 解决方案很好而且很直接,但我仍然会使用 Carbon 来分享我的解决方案。
Carbon is a library included together with laravel and here is the documentation.
Carbon 是一个包含在 laravel 中的库,这里是 文档。
$carbon = new Carbon('Wed Sep 28 2016 01:00:00 GMT+0500 (PKT)');
$carbon->format('Y-m-d H:i:s');
echo $carbon;
it will come out the result same as DateTime
它将得出与 DateTime 相同的结果
2016-09-28 01:00:00
So what carbon nice is you can just add day, minute, second and etc by just a very minimal code, here is an example:
因此,您可以通过一个非常少的代码添加天、分钟、秒等,这是一个例子:
$carbon->addDays(1);
echo $carbon;
//result
2016-09-29 01:00:00
回答by Kinshuk Lahiri
Try this:
尝试这个:
$startTime = strtotime($updatedData['start']);
$time = date("Y-m-d H:i:s",$startTime);
echo date( "Y-M-d H:i:s", strtotime( $time) + 5 * 3600 );
It returns UTC time and you do need to add 5 hours to it. Also a quick suggestion. You can use Carbon for handling the date time.
它返回 UTC 时间,您确实需要为其添加 5 小时。也是一个快速的建议。您可以使用 Carbon 来处理日期时间。
回答by Azeez Kallayi
You can set the desired time zone before converting. Please see the below code as a reference.
您可以在转换前设置所需的时区。请参阅以下代码作为参考。
date_default_timezone_set("Asia/Bangkok");
$str = 'Wed Sep 28 2016 01:00:00 GMT+0500 (PKT)';
$startTime = strtotime($str);
echo $time = date("Y-m-d H:i:s",$startTime);