• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 704
  • Last Modified:

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
0
sabecs
Asked:
sabecs
4 Solutions
 
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
 
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

Featured Post

Vote for the Most Valuable Expert

It’s time to recognize experts that go above and beyond with helpful solutions and engagement on site. Choose from the top experts in the Hall of Fame or on the right rail of your favorite topic page. Look for the blue “Nominate” button on their profile to vote.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now