
本文详解如何解决 PHP 8 下因向 date_create() 传入 null 导致的弃用警告(“Passing null to parameter #1 ($datetime) of type string is deprecated”),并提供健壮、可复用的日期差计算方案。
本文详解如何解决 php 8 下因向 `date_create()` 传入 `null` 导致的弃用警告(“passing null to parameter #1 ($datetime) of type string is deprecated”),并提供健壮、可复用的日期差计算方案。
在 CodeIgniter 4 项目中使用 PHP 8+ 时,若直接将可能为 null 的数据库日期字段(如 $v['sipp_ed'])传递给 date_create(),PHP 会抛出弃用警告:Passing null to parameter #1 ($datetime) of type string is deprecated。这是因为 PHP 8 强化了类型安全性,date_create() 的第一个参数声明为 string 类型,而 null 不符合该类型约束。
根本原因在于:$v['sipp_ed'] 从数据库读取时可能为空(NULL 或空字符串),而未做防御性检查就直接传入日期函数。
✅ 正确做法是始终对输入值进行空值校验与兜底处理。推荐使用空合并运算符 ?? 提供默认值:
Drizzle ORM 是一个轻量级的 TypeScript ORM,提供类型安全的 SQL 模式声明、关系型和类 SQL 查询构建器,以及自动生成迁移。其压缩后仅 7.4kb,且无依赖项,支持 PostgreSQL、MySQL 和 SQLite,包括 Neon、Turso 和 Cloudflare D1 等无服务器数据库。
// 安全创建 DateTime 对象:当 $v['sipp_ed'] 为 null 或未定义时,使用空字符串
$date1 = date_create($v['sipp_ed'] ?? '');
// 更健壮的写法(推荐):显式检查有效性,避免空字符串解析为当前时间
if (empty($v['sipp_ed']) || !is_string($v['sipp_ed']) || !strtotime($v['sipp_ed'])) {
echo "无效或缺失的截止日期,跳过计算。";
$daysDiff = null;
} else {
$date1 = new DateTime($v['sipp_ed']);
$date2 = new DateTime(); // 今天
$interval = $date1->diff($date2);
$daysDiff = (int)$interval->format('%a'); // 获取绝对天数
echo "Difference is {$daysDiff} days";
}
⚠️ 注意事项:
- ❌ 避免
date_create('')或new DateTime(''):空字符串会被解析为当前时间,导致逻辑错误; - ✅ 优先使用面向对象风格(
new DateTime()+->diff()),比过程式date_diff()更清晰且易调试; - ? 在 CI4 中,建议在模型层统一处理日期字段,例如通过
cast属性或访问器(accessor)自动转换或过滤空值; - ? 若需批量处理,可封装为辅助函数:
function daysUntil(string $targetDate, ?string $baseDate = null): ?int
{
if (empty($targetDate) || !strtotime($targetDate)) {
return null;
}
$base = $baseDate ? new DateTime($baseDate) : new DateTime();
$target = new DateTime($targetDate);
return (int)$base->diff($target)->format('%a');
}
// 使用示例:
// $diff = daysUntil($v['sipp_ed']); // 返回天数或 null
总结:该问题本质是 PHP 8 类型严格性升级暴露的旧代码隐患。解决关键不在于更换函数,而在于主动防御 null 输入——结合空值检查、类型验证与语义化默认策略,才能写出兼容 PHP 8+ 且健壮可靠的日期逻辑。










