PHP function to reformat Date 2014/08/27 14:22

Hi,
I need a PHP function to reformat the date below

From 2014/08/27 14:22  to  27th Aug 2014 at 2:22pm

You help would be apprectiated
sabecsAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Guy Hengel [angelIII / a3]Billing EngineerCommented:
0
Ray PaseurCommented:
It's all in here (pay particular attention to ISO-8601):
http://www.experts-exchange.com/Web_Development/Web_Languages-Standards/PHP/A_201-Handling-date-and-time-in-PHP-and-MySQL.html

Please see http://iconoun.com/demo/temp_sabecs.php
<?php // demo/temp_sabecs.php
error_reporting(E_ALL);

// SEE http://www.experts-exchange.com/Programming/Languages/Scripting/PHP/Q_28506178.html
// REF http://www.php.net/manual/en/function.date.php
// From 2014/08/27 14:22  to  27th Aug 2014 at 2:22pm

$original  = '2014/08/27 14:22';
$objective = '27th Aug 2014 at 2:22pm';
$pattern   = 'dS M Y \a\t g:ia';

$timestamp = strtotime($original);
$newstring = date($pattern, $timestamp);
if ($newstring === $objective) echo " SUCCESS! ";

var_dump($objective, $newstring);

Open in new window

0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
MurfurFull Stack DeveloperCommented:
Guy & Ray are both right and the task is pretty straight forward but you have to be careful with date formatting as the core date/time functions can make assumptions that aren't always correct.

For example, it is easy enough to transform your date to the required format as the input date is in a recognised database format of year/month/day etc.
<?
$stringIN	= "2014/08/27 14:22";
$dateIN		= strtotime( $stringIN );
$dateOUT	= date( 'jS M Y'.' @ '.'g:ia', $dateIN );
echo( "IN:  ". $stringIN . "<br />OUT: " . $dateOUT );
?>

Open in new window

This is fine if your input date is always in the same format but what happens if the input date is in a different format  e.g. 08/27/2014? Easy! You say, as it still reads as 27th August. This is true in all cases until your site is international and you encounter an ambiguous date like 12/06/2014 and now the correct answer depends on whether you are from America or Europe. In America, it is 6th December, but in Europe it says 12th June.  strtotime() makes a regional assumption based on the separator found in the string with a / (slash) dictating a US format and - (hyphen) dictating a European format. This is an error (IMHO) as / is commonly used as a short date separator in Europe.
# date with / separators assumed to be US Format
echo( "<b>US Format assumed with / separators</b><br />" );
$stringIN	= "12/06/2014 14:22";
$dateIN		= strtotime( $stringIN );
$dateOUT	= date( 'jS M Y'.' @ '.'g:ia', $dateIN );
echo( "IN:  ". $stringIN . "<br />OUT: " . $dateOUT );
echo("<br /><br />");

# date with - separators assumed to be European Format
echo( "<b>EU Format assumed with - separators</b><br />" );
$stringIN	= "12-06-2014 14:22";
$dateIN		= strtotime( $stringIN );
$dateOUT	= date( 'jS M Y'.' @ '.'g:ia', $dateIN );
echo( "IN:  ". $stringIN . "<br />OUT: " . $dateOUT );
?>

Open in new window

So to future proof your international app the trick is to tell the functions what the format of the input string is and you can do this with date_parse_from_format() which creates an array of the individual date/Time parts. Whether this function gets called or not could be set by a regional user session value.

 You then re-combine the elements into a common format that you can pass to the strtotime() function thus ensuring that your output date is consistent, whatever the reqional source.
<?
# Tell function the format of the input date string
echo( "<b>Manually dictating string format (we use / in Europe too!)</b><br />" );
$stringIN	= "12/06/2014 14:22";
#	creates array from date parts per the specified format
$dateArray	= date_parse_from_format("d/m/Y G:i","12/06/2014 14:22");

#print_r($dateParts);

#	re-join date parts and create timestamp
$dateIN = mktime(
	        $dateArray['hour'], 
	        $dateArray['minute'],
   	        $dateArray['second'],
	        $dateArray['month'],
	        $dateArray['day'], 
	        $dateArray['year']
	);

#	format output date
$dateOUT	= date( 'jS M Y'.' @ '.'g:ia', $dateIN);
echo( "IN:  " . $stringIN . "<br />OUT: " . $dateOUT );
?>

Open in new window

0
Ray PaseurCommented:
@murfur: Good comment, and it further underscores the principle of using ISO-8601 format date/time values for all internal representations.  I've used this little script to test the PHP strtotime() function.  It seems to get it mostly right, most of the time.
http://iconoun.com/demo/strtotime.php
<?php // demo/strtotime.php
error_reporting(E_ALL);

// RESPONSE STRING HERE
$obuff = NULL;

// MAN PAGE http://php.net/manual/en/datetime.formats.relative.php
// MAN PAGE http://php.net/manual/en/function.date-default-timezone-set.php
date_default_timezone_set('America/Chicago');

// IF WE HAVE INPUT FROM THE URL QUERY STRING
if (!empty($_GET["s"]))
{
    // COLLECT THE OUTPUT BUFFER
    ob_start();

    // USE strtotime() FUNCTION TO MAKE A TIMESTAMP
    // MAN PAGE: http://php.net/manual/en/function.strtotime.php
    $unix_timestamp = strtotime($_GET["s"]);

    // TEST FOR SUCCESS OR FAILURE
    if ($unix_timestamp === FALSE)
    {
        echo "<strong>HONK!</strong><br /> <u>{$_GET["s"]}</u> NOT USEFUL WITH strtotime() <br/><br/><br/><br/>";
    }

    // ON SUCCESS, PRINT THE RESULTS
    else
    {
        echo "<strong>BINGO</strong><br /> <strong><u>{$_GET["s"]}</u></strong> WORKS WITH strtotime() <br/>";
        echo "THE INTEGER TIMESTAMP VALUE IS ";
        echo number_format($unix_timestamp) . "<br />";

        // FORMAT ISO AND HUMAN-READABLE DATES
        // MAN PAGE: http://php.net/manual/en/function.date.php
        $y = date('c', $unix_timestamp);
        echo "THE ISO8601 DATETIME STRING IS $y<br />";
        $z = date('l dS \o\f F Y g:i:s A', $unix_timestamp);
        echo "THE TEXTUAL DATE IS $z<br />";
    }

    // RECOVER THE RESPONSE FROM THE OUTPUT BUFFER
    $obuff = ob_get_clean();

} // END OF PROCESSING INPUT

$tzone = date_default_timezone_get();
$phpvs = phpversion();

// CREATE THE HTML FORM USING HEREDOC NOTATION
$htmls = <<<HTMLS
<!DOCTYPE html>
<html dir="ltr" lang="en-US">
<head>
<meta charset="iso-8859-1" />
<title>PHP strtotime()</title>
</head>

<body onload="document.f.s.focus()">

$obuff

<form name="f" method="get">
<br />TO TEST A STRING FOR A VALID DATE/TIME, TYPE IT HERE:<input name="s" />
<input type="submit" value="GO" />
</form>

<br/><strong>Note: Your local time may vary.  This server is in $tzone</strong>
<br/>Current PHP version is $phpvs
<br/>TRY TESTING SOME OF THESE STRINGS (CLICK THE LINK, OR COPY AND PASTE INTO THE FORM):
HTMLS;

echo $htmls;

// DEFINE A FUNCTION TO CREATE A TEST CASE
function t($str)
{
    echo PHP_EOL
    . '<br/>'
    . '<a href="http://iconoun.com/demo/strtotime.php?s='
    . urlencode($str)
    . '">'
    . $str
    . '</a>'
    ;
}

// USE THE FUNCTION TO CREATE A FEW TEST CASES
t('- 3 hours');
t('tomorrow');
t('tomorrow 3:15:25 pm');
t('March 15, 1986');
t('yesterday');
t('yesterday + 1 week');
t('next year');
t('now');
t('now + 627 hours 15 minutes');
t('tomorrow midnight');
t('tomorrow 1:35pm');
t('last Tuesday');
t('three days ago');
t('last Friday + 2 weekdays');
t('- 3 days');
t('A TIME');
t('A BOGUS TIME');
t('s time');
t('t time');
t('u time');
t("Avogadro's Constant");
t("Wednesday November, 10 2010 1:01pm");
t("Wednesday, November 10 2010 1:01pm");
t("First Tuesday 2005"); echo " works, but not the way you might think";
t("Last day of January + 1 Month"); echo " works, but not the way you might think";
t("January 31 + 1 Month"); echo " works, but not the way you might think";
t('-1000000000 seconds'); echo " one billion";
t('+1000000000 seconds');
t('42'); echo " and thanks for all the fish!";

// END OF PAGE
echo '</body></html>';

Open in new window

0
sabecsAuthor Commented:
Thanks for all your help.
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
PHP

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.