开发者

How to format this date (dd/mm/yyyy) into (j M Y) in PHP? [closed]

开发者 https://www.devze.com 2023-03-20 01:50 出处:网络
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical andcannot be reasonably answered in its current form. For help clari
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center. Closed 11 years ago.

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号