rob.m
rob.m

Reputation: 10591

How do I use an instance of class DateTime to output its date?

I need to create a date and the I need to show it, I tried:

$myDate = DateTime::createFromFormat('d-m-yy', usp_get_meta(false,'usp-custom-80')); 
echo date("d-m-yy", $myDate);

But nothing shows up, if I var_dump($mydate); it is fine, it is a correct date object

Upvotes: 1

Views: 483

Answers (3)

Mirko Steiner
Mirko Steiner

Reputation: 374

You mixed a bit stuff up in your code.

  1. in line 1 you assign instance (object) of class DateTime to $myDate - thats ok!
  2. in line 2 you want to output with echo the return value of the function date() which is a string BUT the second argument has to be a integer and not an object of class DateTime -- thats what you have mixed up

you can use the format method on the DateTime class to get the saved date in the way you want it and give it to echo:

echo $myDate->format("d-m-y");

http://php.net/manual/en/datetime.format.php gives mor information about the DateTime::format() method.

You should gain more experience with procedural and objective programming, seems to me, that you mix some stuff up.

Also a PHP tutorial may be very helpfull

Upvotes: 1

A l w a y s S u n n y
A l w a y s S u n n y

Reputation: 38542

First of all you've try like this way.(I'm little bit confused why you've used 2 yy?)

# you've to set the 'd-m-Y' based on your usp_get_meta() value
$myDate = DateTime::createFromFormat('d-m-Y', usp_get_meta(false,'usp-custom-80'));
echo $myDate ->format('d-m-Y');

To get why your existing code not working?

Try to get the last error using- var_dump(DateTime::getLastErrors());

DEMO: https://3v4l.org/rq9tA

Upvotes: 0

Dan
Dan

Reputation: 11104

To output the date in a string format use DateTime::format() http://php.net/manual/en/datetime.format.php

echo $myDate->format("d-m-Y");

date() is for formatting timestamp integers. http://php.net/manual/en/function.date.php

Upvotes: 2

Related Questions