How to format this date (dd/mm/yyyy) into (j M Y) in PHP? [closed]
I'm trying to convert this date format (in PHP): "dd/mm/yyyy", for example 18/08/2011, int开发者_JS百科o "j M Y" which should output something like this, "18 August 2011".
If anyone could help, it would be much appreciated, Thanks.
If you are using PHP >= 5.3 you may try the DateTime class.
<?php
$dateString = '18/08/2011';
$dt = DateTime::createFromFormat('d/m/Y', $dateString);
echo date('d M Y', $dt->getTimestamp());
?>
<?php
$str = "18/08/2011";
preg_match("|(.*?)/(.*?)/(.*?)|", $str, $match);
$str = $match[2]."/".$match[1]."/".$match[2];
echo $your_format = date("j M Y", strtotime($str)); //strtotime() expects mm/dd/yyyy
//returns 18 Aug 2008
?>
http://sandbox.phpcode.eu/g/29439.php
strtotime() is fine, but it runs the risk of returning unexpected results due to the date configuration of your system. Just to be extra safe, I favour using a look-up array.
<?php
function dateReformat( $date )
{
$monthList = array
(
'January',
'February',
'March',
'April',
'May',
'June',
'July',
'August',
'September',
'October',
'November',
'December'
);
$tmp = explode( '/', $date );
$month = $monthList[ $tmp[1]-1 ];
return "{$tmp[0]} {$month} {$tmp[2]}";
}
echo dateReformat( '12/05/1980' );
Here is one way:
$oldDate = "18/08/2011";
$dateArr = explode("/", $oldDate);
$newDate = date("j M Y", mktime(0,0,0,$dateArr[1],$dateArr[0],$dateArr[2]));
Should work as is. Notice the order of the $dateArr
elements listed in mktime
.
精彩评论