Hi, I want to convert this date format 18/4/2013 to this format 2013-04-18 How i can do this with PHP? thanks in advance.
Hm, DateTime is a good solution, though I'm not too sure if d/m/Y is a valid format you can pass through to the class constructor. I suspect it may raise an exception. Likewise, you may not be able to convert that string to a Unix timestamp using strtotime in that format as well (though it's worth trying). If that's the case, a simple solution may be to do something like: <?php list($day, $month, $year) = explode('/', '18/4/2013'); $convertedDate = sprintf('%s-%s-%s', $year, $month, $day); var_dump($convertedDate); PHP: Output: string(9) "2013-4-18" Code (markup):
this is my solution $md = explode("/", "18/4/2013"); // split the array $nd = $md[2]."-".$md[1]."-".$md[0]; // join them together $mydate = date('Y-m-d', strtotime($nd)); PHP:
I suggest using strtotime function to convert the date to a unix timestamp, then you can display it on any format you wish, eg: $format1 = "18/4/2013"; $timestamp = strtotime($format1); $format2 = date("Y-m-d", $timestamp); Code (markup):
Relying on php date functions such as strtotime is not safe, because they are using server's locale which also describes date and time formats. You need to specify both formats: <? $dt = DateTime::createFromFormat("d/m/Y", "18/4/2013"); echo $dt->format("Y-m-d"); ?> Code (markup):
This will not work, since your format is: d/m/Y. As stated on the manual: Which is the solution Alex Raven posted.
You can use explode to break string into array using $arr=explode("-",$da); and then reverse array using array_reverse($arr); and then implode an array using $str= implode("-",$arr); so you will get your result in the $str