开发者

PHP Datetime not working properly

I am retrieving the datetime data from mysql the retrieved data from a single row is.

2011-04-11 19:31:30 

I wanted to reformat the datetime in d-m-Y H:i:s for that I am using date_format() the below code works just fine.

$date = new DateTime($users['registerDate']);
echo开发者_运维技巧 $date->format('d-m-Y H:i:s');

However, I don't want to go object oriented way just for reformatting because I will be using the code within the foreach loop and that means I would have to initialize the DateTime class again and again.

I tried doing this the Procedural way using the following code.

$date = $users['registerDate'];
echo date_format($date, 'Y-m-d H:i:s');

the above code does not work for me and gives back the following error.

Warning: date_format() expects parameter 1 to be DateTime, string given in /Applications/MAMP/htdocs/kokaris/administrator/resources/library/models/users/users.php on line 21

What could be possibly wrong?

The given solution works perfectly fine for the procedural way.

echo date('m-d-Y',strtotime($users['registerDate']));

However I would like to know which will be the best feasible solution the above procedural way or the OOP way.

 $date = new DateTime($users['registerDate']);
 echo $date->format('d-m-Y H:i:s');

Considering I will be using the code within a foreach loop and it may loop for over a hundred times.


You do not need "date_format()":

echo date('d-m-Y H:i:s', strtotime('2011-04-11 19:31:30'));

//results: 11-04-2011 19:31:30


You're trying to use a function/object that is part of the DateTime class without creating a reference to the DateTime class.

For procedural formatting take a look at date()


What you are seeking for is this:

date('d-m-Y H:i:s', strtotime('2011-04-11 19:31:30'));

Have a look at the php-manual. However, using the methods you yourself proposed is pretty fine, since the DateTime-object maps to some functions written in C.

Also PHP Datetime is working properly, since date_format is just an alias of Date::format, which does exactly require what you don’t want to pass in (a DateTime-object).

Honestly, we’re talking about PHP...

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜