Carol.Kar
Carol.Kar

Reputation: 5355

getTimestamp() - Fatal Error when call to a member function

I would like to convert the following string to datetime:

<?php
$t = '2017-12-22T11:46:21.647+00:00';

$date = date_create_from_format('d/M/Y:H:i:s', $t);
print_r($date->getTimestamp());

However, I get the following error:

Fatal error: Call to a member function getTimestamp() on a non-object in /home/ubuntu/workspace/src/t02-convertDateTime.php on line 5

Any suggestions why?

Upvotes: 2

Views: 13529

Answers (2)

Pasindu
Pasindu

Reputation: 81

The problem is the way that you given the format. Try this one or check PHP Mannual

$t = '2017-12-22 11:46:21';

$date = date_create_from_format('Y-m-d H:i:s', $t);
var_dump($date->getTimestamp());

Upvotes: 0

Soolie
Soolie

Reputation: 1797

When you execute this code:

<?php
$t = '2017-12-22T11:46:21.647+00:00';

$date = date_create_from_format('d/M/Y:H:i:s', $t);
var_dump($date);
print_r($date->getTimestamp());

You get the following output:

bool(false) 
FATAL ERROR Uncaught Error: Call to a member function getTimestamp() on boolean in /home4/phptest/public_html/code.php70(5) : eval()'d code:6 Stack trace: #0 /home4/phptest/public_html/code.php70(5): eval() #1 {main} thrown on line number 6

Looks like it's an Invalid Date Format. You need to get the right date format.

Also in the manual, there's a comment saying:

There is no option to specify date format 'c' (e.g. 2004-02-12T15:19:21+00:00) directly. work around is to use Y-m-d\TH:i:sT

An alternate to this is:

<?php
$t = '2017-12-22T11:46:21.647+00:00';

var_dump(date("Y-m-d g:i:s a", strtotime("2017-12-22T11:46:21.647+00:00")));

And this gives you:

2017-12-22 6:46:21 am

Upvotes: 3

Related Questions