PHP convert date format dd/mm/yyyy => yyyy-mm-dd [duplicate]

匿名 (未验证) 提交于 2019-12-03 02:14:01

问题:

Possible Duplicate:
PHP Date String Format

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 '-'.

Any help will be greatly appreciated.

回答1:

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.

Use the default date function.

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

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));


回答2:

Try Using DateTime::createFromFormat http://www.php.net/manual/en/datetime.createfromformat.php

$date = DateTime::createFromFormat('d/m/Y', "24/04/2012"); echo $date->format('Y-m-d');

Output

2012-04-24


回答3:

Here's another solution not using date(). not so smart:)

$var = '20/04/2012'; echo implode("-", array_reverse(explode("/", $var)));


回答4:

Do this:

date('Y-m-d', strtotime('dd/mm/yyyy'));

But make sure 'dd/mm/yyyy' is the actual date.



回答5:

I did like to note that it'd be better when programming to use Timestamp than actual date to represent time, you can then use PHP to transform the "timestamp" value to any format of date you'd want.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!