PHP转换日期格式dd/mm/yyyy =>yyyy-mm-dd

2022-01-12 00:00:00 date formatting php mktime

我正在尝试将日期从 dd/mm/yyyy =>yyyy-mm-dd.我使用了 mktime() 函数和其他函数,但我似乎无法使其工作.我已经设法explode 使用 '/' 作为分隔符的原始日期,但我没有成功更改格式并交换 '/'带有 '-'.

I am trying to convert a date from dd/mm/yyyy => yyyy-mm-dd. I have using the mktime() function and other functions but I cannot seem to make it work. I have managed to explode the original date using '/' as the delimiter but I have no success changing the format and swapping the '/' with a '-'.

任何帮助将不胜感激.

推荐答案

m/d/yd-m-y 格式的日期可以通过查看来消除歧义在各个组件之间的分隔符处:如果分隔符是斜杠 (/),则假定为美式 m/d/y;而如果分隔符是破折号 (-) 或点 (.),然后是欧式 d-m-y假定格式.在这里查看更多.

Dates in the m/d/y or d-m-y formats are disambiguated by looking at the separator between the various components: if the separator is a slash (/), then the American m/d/y is assumed; whereas if the separator is a dash (-) or a dot (.), then the European d-m-y format is assumed. Check more here.

使用默认日期函数.

$var = "20/04/2012";
echo date("Y-m-d", strtotime($var) );

EDIT 我刚刚测试过,不知何故,PHP 不能很好地与 dd/mm/yyyy 格式一起工作.这是另一个解决方案.

EDIT I just tested it, and somehow, PHP doesn't work well with dd/mm/yyyy format. Here's another solution.

$var = '20/04/2012';
$date = str_replace('/', '-', $var);
echo date('Y-m-d', strtotime($date));

相关文章