1

I have problems getting the date from a DateTime object. I use code like print_r($value->created_at) and it shows me

DateTime Object 
( 
    [date] => 2018-03-10 12:53:18.000000
    [timezone_type] => 1 
    [timezone] => +02:00 
) tablet

Now how to get this [date]? I tried with different ways like $value->created_at->date and $value->created_at["date"] but it does not work out.

4
  • Already said that doesn't work. Undefined property: DateTime::$date Commented Mar 29, 2018 at 11:14
  • $date = $value->created_at;echo $date->format('Y-m-d'); Commented Mar 29, 2018 at 11:14
  • Your object is a Datetime object, use $value->created_at->format('Y-m-d'); Commented Mar 29, 2018 at 11:17
  • What error are you getting. Please show us the FULL error message Commented Mar 29, 2018 at 11:20

3 Answers 3

3

The names in the [] are the names of the objects properties so

$value->created_at->date
$value->created_at->timezone_type
$value->created_at->timezone

are the only properties available to you

Example

$d = new DateTime('now');
print_r($d);

echo $d->date . PHP_EOL;
echo $d->timezone_type . PHP_EOL;
echo $d->timezone . PHP_EOL;

Result:

DateTime Object
(
    [date] => 2018-03-29 11:17:19.000000
    [timezone_type] => 3
    [timezone] => UTC
)
2018-03-29 11:17:19.000000
3
UTC

If you want convert the date to be a specific format then you can use the ->format() method like this

echo $d->format('d/m/Y h:s');

Result

29/03/2018 11:37
Sign up to request clarification or add additional context in comments.

3 Comments

Accessing those properties directly is rather dangerous though, try to echo date before doing a print_r on $d and it doesn't exist.
@ChristianM Agreed, but as OP was trying that I thought I would start there and then gently introduce the ->format() functionality
You are right of course :) I just tend to avoid showing ungood example code, because in a hurry someone might just copy paste that :D
2

This is a \DateTime object http://php.net/manual/en/class.datetime.php

You can get a string representation of the date as you see when var_dumping by using the format method:

$value->created_at->format(\DateTime::ISO8601);

Note that I used the ISO8601 format, you can give any format string you want or use one of the predefined ones, depending on how you want to use this string.

Comments

0

Use this ways,

$date = $value->created_at;
echo $date->format('Y-m-d');

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.