首页 > 解决方案 > PHP DateTime::__construct():无法解析位置 8 (0) 的时间字符串:意外字符

问题描述

DateTime使用课程时出现以下错误

DateTime::__construct():无法在位置 8 (0) 解析时间字符串 (1607990400):意外字符

代码

// post meta returns below value
// 1607990400

$wp_timezone = get_option('timezone_string');
$timezone    = $wp_timezone ? $wp_timezone : 'UTC';

new DateTime(get_post_meta($group_id, 'last_date', TRUE), new DateTimeZone($timezone));

标签: phpdatetime

解决方案


DateTime不期望在构建时有一个 Unix 时间戳。所以你必须使用createFromFormat方法:

$dt = DateTime::createFromFormat(
    'U', 
    get_post_meta($group_id, 'last_date', TRUE), 
    new DateTimeZone($timezone)
);

推荐阅读