阅读量:132
strtotime() 是 PHP 中的一个非常有用的函数,用于将任何英文文本的日期时间描述解析为 Unix 时间戳
- 检查输入是否为空:确保传递给
strtotime()的字符串不为空,否则会返回一个错误。
$date = "";
if ($date === "") {
echo "Error: Date string is empty.";
} else {
$timestamp = strtotime($date);
if ($timestamp === false) {
echo "Error: Invalid date format.";
} else {
echo "The timestamp is: " . $timestamp;
}
}
- 使用
try-catch语句处理异常:如果你在使用 PHP 7 或更高版本,可以使用try-catch语句捕获DateTimeException异常,这是strtotime()函数在遇到错误时抛出的异常类型。
$date = "invalid_date";
try {
$timestamp = strtotime($date);
if ($timestamp === false) {
throw new DateTimeException("Invalid date format.");
} else {
echo "The timestamp is: " . $timestamp;
}
} catch (DateTimeException $e) {
echo "Error: " . $e->getMessage();
}
这两种方法都可以帮助你处理 strtotime() 函数可能出现的错误。确保始终验证和清理用户输入,以避免潜在的安全问题。