Fetch date from Carbon\Carbon Object
Asked Answered
T

3

6

I am getting a Collection which contains

  [80] => Array
            (
                [date] => Carbon\Carbon Object
                    (
                        [date] => 2018-04-04 17:27:24.000000
                        [timezone_type] => 3
                        [timezone] => UTC
                    )

I want to get the date from here, when I do foreach it gives a Carbon\Carbon Object('date' like this, but then can not access date.

Does anyone know any solution?

Torsion answered 4/4, 2018 at 17:46 Comment(0)
T
3

$analyticsData = Analytics::fetchVisitorsAndPageViews(Period::days(7));

   foreach($analyticsData as $data)
   {
       print_r($data['date']->toDateString());die;
   }
Torsion answered 4/4, 2018 at 18:4 Comment(0)
H
3

If you like to convert to string, use

$data['date']->toDateTimeString()

Or you can format custom

$data['date']->format('Y/m/d H:i')
Harim answered 19/10, 2018 at 11:16 Comment(1)
Works in Laravel-08Borden
R
0

Carbon is a nice wrapper around dates. It has a really great API to get things like date subtraction, testing if a date is in a range, formatting dates, etc.

It sounds like you're looking to format an array of Carbon objects to a date.

You can use array_map to produce this kind of result:

$dates_formatted = array_map(function($entry) {
    // transform the Carbon object to something like 'Dec 25, 1975'
    return $entry['date']->toFormattedDateString();  
}, $dates);

Note: I'm assuming your array is named $dates. If you want a more accurate answer, provide the whole output of your collection along with the name of the variable.

To try out other date formatting options check out their (awesome) documentation: https://carbon.nesbot.com/docs/#api-formatting

Ribal answered 4/4, 2018 at 17:59 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.