如何将日期格式 d/m/Y 更改为 Ymd PHP
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20868464/
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
How to change date format d/m/Y to Y-m-d PHP
提问by user3099298
I want to keep date format d/m/Y (24/12/2013) in client side (users enter date in that format from JQuery date picker). But in server side I convert it to Y-m-d(2013-12-24) format.
我想在客户端保留日期格式 d/m/Y (24/12/2013)(用户从 JQuery 日期选择器输入该格式的日期)。但在服务器端,我将其转换为 Ymd(2013-12-24) 格式。
To do that I wrote code in this way
为此,我以这种方式编写了代码
$brithdate = explode('/', $_POST['brithday']);
$brithdateFormated = $brithdate[2] . "-" . $brithdate[1] . "-" . $brithdate[0];
Is this correct? or is there any easy way to do that
这样对吗?或者有什么简单的方法可以做到这一点
回答by Amal Murali
Use DateTime objects when you're working with dates and times. You can use DateTime::createFromFormat()to parse the date string and then the DateTime::format()to format it the way you want:
在处理日期和时间时使用 DateTime 对象。您可以使用 DateTime::createFromFormat()解析日期字符串,然后DateTime::format()按照您想要的方式对其进行格式化:
$str = '24/12/2013';
$date = DateTime::createFromFormat('d/m/Y', $str);
echo $date->format('Y-m-d'); // => 2013-12-24
For a list of available formatting options, see the documentation.
有关可用格式选项的列表,请参阅文档。
回答by Rizwan Sultan
Try this
尝试这个
$birthdate= strtotime($_POST['brithday']);
$brithdateFormated = date("d/m/Y",$birthdate);
回答by Parth Patel
This is working for me.
这对我有用。
$start_date='04/05/2018';
$convertedDate= DateTime::createFromFormat('d/m/Y', $start_date)->format('Y-m-d');
Note: The First parameter should be same as your $start_date with '/' also. If you put '-' there, then it will not perform the correct conversion.
注意:第一个参数也应该与您的 $start_date 相同,并带有“/”。如果你把'-'放在那里,那么它不会执行正确的转换。

