PHP 处理非标准时间字符串:将 '25/11/2020下午4:00:00' 转换为标准时间格式
可以使用 strtotime() 函数将字符串转换为时间戳,再用 date() 函数将时间戳格式化为标准时间格式。
例如:
$time_str = '25/11/2020下午4:00:00';
$time_stamp = strtotime(str_replace('下午', 'PM', str_replace('上午', 'AM', $time_str)));
$standard_time = date('Y-m-d H:i:s', $time_stamp);
echo $standard_time;
输出结果为:2020-11-25 16:00:00
解释:
- 首先使用
str_replace()函数将 '上午' 替换为 'AM',将 '下午' 替换为 'PM',得到标准的时间字符串。 - 然后使用
strtotime()函数将时间字符串转换为时间戳。 - 最后使用
date()函数将时间戳格式化为标准时间格式。注意,在使用date()函数时需要注意时区的设置,否则可能会输出错误的时间。
原文地址: https://www.cveoy.top/t/topic/lBmX 著作权归作者所有。请勿转载和采集!