rest_parse_date()
云策文档标注
概述
rest_parse_date() 函数用于将 RFC3339 格式的时间字符串解析为 Unix 时间戳。它支持可选参数强制使用 UTC 时区,并返回时间戳或 false 表示失败。
关键要点
- 函数将 RFC3339 时间字符串转换为 Unix 时间戳,成功时返回 int,失败时返回 false。
- 参数 $force_utc 可选,默认为 false,设置为 true 可强制使用 UTC 时区。
- 使用正则表达式验证输入格式,失败时返回 false。
- 注意:成功时可能返回 0(有效时间戳),需显式检查 false 以检测失败。
代码示例
function rest_parse_date( $date, $force_utc = false ) {
if ( $force_utc ) {
$date = preg_replace( '/[+-]d+:?d+$/', '+00:00', $date );
}
$regex = '#^d{4}-d{2}-d{2}[Tt ]d{2}:d{2}:d{2}(?:.d+)?(?:Z|[+-]d{2}(?::d{2})?)?$#';
if ( ! preg_match( $regex, $date, $matches ) ) {
return false;
}
return strtotime( $date );
}注意事项
- 成功时可能返回 0(如 1970-01-01T00:00:00Z),需用 false 检查失败,而非零值。
- 函数自 WordPress 4.4.0 版本引入。
原文内容
Parses an RFC3339 time into a Unix timestamp.
Description
Explicitly check for false to detect failure, as zero is a valid return value on success.
Parameters
$datestringrequired-
RFC3339 timestamp.
$force_utcbooloptional-
Whether to force UTC timezone instead of using the timestamp’s timezone.
Default:
false
Source
function rest_parse_date( $date, $force_utc = false ) {
if ( $force_utc ) {
$date = preg_replace( '/[+-]d+:?d+$/', '+00:00', $date );
}
$regex = '#^d{4}-d{2}-d{2}[Tt ]d{2}:d{2}:d{2}(?:.d+)?(?:Z|[+-]d{2}(?::d{2})?)?$#';
if ( ! preg_match( $regex, $date, $matches ) ) {
return false;
}
return strtotime( $date );
}
Changelog
| Version | Description |
|---|---|
| 4.4.0 | Introduced. |