Reputation: 3754
I'm maintaining PHP code which seems to mess up date/time handling rather badly. In particular this application does not work well in other locales.
One of the issues is the use of the non-localizable date()
function instead of the strftime()
function. It is used several layers deep inside function which are literally used thousands of times with many different format strings all over the place.
Replacing date()
with strftime()
would cost way too much time. Rather I'm looking into ways to have strftime()
handle the same format strings as date()
, but can't find anything. Is there any known solution to use strftime()
with date()
format strings?
Upvotes: 3
Views: 3798
Reputation: 1810
/**
* Convert strftime format to php date format
* @param $strftimeformat
* @return string|string[]
* @throws Exception
*/
function strftime_format_to_date_format($strftimeformat){
$unsupported = ['%U', '%V', '%C', '%g', '%G'];
$foundunsupported = [];
foreach($unsupported as $unsup){
if (strpos($strftimeformat, $unsup) !== false){
$foundunsupported[] = $unsup;
}
}
if (!empty($foundunsupported)){
throw new \Exception("Found these unsupported chars: ".implode(",", $foundunsupported).' in '.$strftimeformat);
}
// It is important to note that some do not translate accurately ie. lowercase L is supposed to convert to number with a preceding space if it is under 10, there is no accurate conversion so we just use 'g'
$phpdateformat = str_replace(
['%a','%A','%d','%e','%u','%w','%W','%b','%h','%B','%m','%y','%Y', '%D', '%F', '%x', '%n', '%t', '%H', '%k', '%I', '%l', '%M', '%p', '%P', '%r' /* %I:%M:%S %p */, '%R' /* %H:%M */, '%S', '%T' /* %H:%M:%S */, '%X', '%z', '%Z',
'%c', '%s',
'%%'],
['D','l', 'd', 'j', 'N', 'w', 'W', 'M', 'M', 'F', 'm', 'y', 'Y', 'm/d/y', 'Y-m-d', 'm/d/y',"\n","\t", 'H', 'G', 'h', 'g', 'i', 'A', 'a', 'h:i:s A', 'H:i', 's', 'H:i:s', 'H:i:s', 'O', 'T',
'D M j H:i:s Y' /*Tue Feb 5 00:45:10 2009*/, 'U',
'%'],
$strftimeformat
);
return $phpdateformat;
}
I wrote this function because none of the answers above sufficed. Handles most conversions -- easily extendable.
@see https://www.php.net/manual/en/function.date.php and https://www.php.net/manual/en/function.strftime.php
Upvotes: 7
Reputation: 11
Example for from date() to strftime(). Thanks Kick_the_BUCKET
$search = array('Y', 'y', 'M', 'm', 'D', 'd');
$replace = array('%Y', '%y', '%B', '%b', '%A %d', '%A %d');
$dateFormat = str_replace($search, $replace, $dateFormat); ?>
echo $dateFormat
Upvotes: 0
Reputation: 2149
I'm guessing that you need to convert the format, that is currently used by date()
function into a format, that strftime()
could use.
For that purpose I would suggest using str_replace()
with arrays as search
and replace
arguments:
$oldFormat = 'Y-m-d';
$search = array('Y', 'm', 'd');
$replace = array('%Y', '%m', '%d');
$newFormat = str_replace($search, $replace, $oldFormat);
Of course, you should add all the search and replace terms that you would need to convert.
Upvotes: 0