我正在维护的PHP代码似乎搞砸了日期/时间处理相当严重。特别是,这个应用程序在其他地区不能很好地工作。
其中一个问题是使用不可本地化的date()
函数而不是strftime()
函数。它在函数内部的几个层中使用,实际上使用了数千次,并且到处都有许多不同的格式字符串。
用strftime()
代替date()
将花费太多时间。相反,我正在研究如何让strftime()
处理与date()
相同的格式字符串,但找不到任何东西。是否有任何已知的解决方案使用strftime()
与date()
格式字符串?
/**
* 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;
}
我写这个函数是因为上面的答案都不满足。处理大多数转换-易于扩展。
@see https://www.php.net/manual/en/function.date.php和https://www.php.net/manual/en/function.strftime.php
我猜你需要转换格式,这是目前由date()
函数使用的格式,strftime()
可以使用。
为了这个目的,我建议使用str_replace()
和数组作为search
和replace
参数:
$oldFormat = 'Y-m-d';
$search = array('Y', 'm', 'd');
$replace = array('%Y', '%m', '%d');
$newFormat = str_replace($search, $replace, $oldFormat);
当然,您应该添加所有需要转换的搜索和替换词
从date()到strftime()的示例。由于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