note 50543 deleted from function.strtotime by derick
| From: | derick@php.net | Date: | Sun, 14 Aug 2005 11:58:23 +0000 |
| Subject: | note 50543 deleted from function.strtotime by derick | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-93605@lists.php.net to get a copy of this message | ||
Note Submitter: jason at draxjinn dot com
----
After searching the (entire) internet for a routine that would (re)format a date string without the
pre-1970 problems of strtotime, I ended up writing the following function. [Note that it
doesn't support all of the formatting options that the date() function does, but it is really a
trivial matter to implement the remaining features.]
(Thanks to Jan Goyvaerts site http://www.regular-expressions.info/dates.html
for having the snippets of regular expressions that parse the date formats)
Hope this helps:
function formatDate($szFormat, $szDate = NULL)
{
if (!isset($szDate))
$szDate = date("Y-m-d H:i:s");
$szTemp = "00-00-0000";
$arryMatch = Array();
if ( preg_match('%(19|20)\d\d[- /.](0[1-9]|1[012])[- /.](0[1-9]|[12][0-9]|3[01])%',
$szDate, $arryMatch) )
{
// Date is in the format of Y-m-d
$arryTemp = preg_split('%[- /.]%', $arryMatch[0]);
$arryDate['m'] = $arryTemp[1];
$arryDate['d'] = $arryTemp[2];
$arryDate['Y'] = $arryTemp[0];
//$szTemp = .'-'.$arryTemp[2].'-'.$arryTemp[0];
}
elseif ( preg_match('%(0[1-9]|1[012])[- /.](0[1-9]|[12][0-9]|3[01])[- /.](19|20)\d\d%',
$szDate, $arryMatch) )
{
// Date is in the format of m-d-Y
$arryTemp = preg_split('%[- /.]%', $arryMatch[0]);
$arryDate['m'] = $arryTemp[0];
$arryDate['d'] = $arryTemp[1];
$arryDate['Y'] = $arryTemp[2];
//$szTemp = $arryTemp[0].'-'.$arryTemp[1].'-'.$arryTemp[2];
}
elseif ( preg_match('%(0[1-9]|[12][0-9]|3[01])[- /.](0[1-9]|1[012])[- /.](19|20)\d\d%',
$szDate, $arryMatch) )
{
// Date is in the format of d-m-Y
$arryTemp = preg_split('%[- /.]%', $arryMatch[0]);
$arryDate['m'] = $arryTemp[1];
$arryDate['d'] = $arryTemp[0];
$arryDate['Y'] = $arryTemp[2];
//$szTemp = $arryTemp[1].'-'.$arryTemp[2].'-'.$arryTemp[2];
}
if (!checkdate($arryDate['m'], $arryDate['d'], $arryDate['Y']))
{
return -1;
}
$nJD = gregoriantojd($arryDate['m'], $arryDate['d'],
$arryDate['Y']);
$szTemp = str_replace('Y', $arryDate['Y'], $szFormat);
$szTemp = str_replace('m', $arryDate['m'], $szTemp);
$szTemp = str_replace('d', $arryDate['d'], $szTemp);
$szTemp = str_replace('D', jddayofweek( $nJD, 2), $szTemp);
$szTemp = str_replace('F', jdmonthname( $nJD, 1), $szTemp);
//echo $szTemp;
return $szTemp;
}