1

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

2 Answers 2

4

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)
);
Sign up to request clarification or add additional context in comments.

Comments

0

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', ..

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.