Code Lover
Code Lover

Reputation: 8348

PHP DateTime::__construct(): Failed to parse time string at position 8 (0): Unexpected character

I am getting the below error while using the DateTime class

DateTime::__construct(): Failed to parse time string (1607990400) at position 8 (0): Unexpected character

Code

// 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));

Upvotes: 1

Views: 3465

Answers (2)

jspit
jspit

Reputation: 7703

If you concatenated the '@' with a Unix timestamp, DateTime can handle this.

$getPostMeta = '1607990400';  //Unix-Timestamp
$dt = new DateTime('@'.$getPostMeta);
echo $dt->format('Y-m-d H:i');  //2020-12-15 00:00

The time zone is always "+00: 00" (UTC)! If a time zone is set as an optional parameter, this is ignored.

This also applies to DateTime :: createFromFormat ('U', ..

Upvotes: 0

Sindhara
Sindhara

Reputation: 1473

DateTime does not expect an unix timestamp at construction. So you have to use the createFromFormat method:

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

Upvotes: 4

Related Questions