如何更改日期格式d/m/Y到Y-m-d PHP ?

时间:2022-06-29 21:26:48

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 date picker输入该格式的日期)。但在服务器端,我将其转换为Y-m-d(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

这是正确的吗?或者有什么简单的方法。

2 个解决方案

#1


21  

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.

有关可用格式化选项的列表,请参阅文档。

#2


3  

Try this

试试这个

$birthdate= strtotime($_POST['brithday']);
$brithdateFormated = date("d/m/Y",$birthdate);

#1


21  

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.

有关可用格式化选项的列表,请参阅文档。

#2


3  

Try this

试试这个

$birthdate= strtotime($_POST['brithday']);
$brithdateFormated = date("d/m/Y",$birthdate);