简体   繁体   中英

Laravel-Excel 2, get the year and month from “date” in Carbon format

In Laravel-Excel 2, I'm reading a file like this:

在此处输入图片说明

The code to read it is this:

$my_file ='some/path/to/my_file.xls';
$data = Excel::selectSheetsByIndex(0)->load($my_file, function($reader) {})->get()->toArray();

This it the output for dd($data[0]); , considering that data is an array:

在此处输入图片说明

I need to get the year (2005) and month (11) from "date". "date" is inside "fecha" and it is in Carbon format. How can I get it? I've been having a lot of problems reading that array-object thing. I thought that $data[0]["fecha"]->date would do the trick but, instead of that it works with:

$data[0]["fecha"].["date"]

But I'm having some errors in some versions of php with "Array to string conversion", but in my php it doesn't show the error, so how should I get that year and month? I don't get it.

This is the output of print_r($data[0]);die(); :

Array (
    [fecha] => Carbon\Carbon Object (
        [date] => 2005-11-01 00:00:00.000000 [timezone_type] => 3 [timezone] => America/Santiago 
    ) 
    [hora] => 
    [bloquefr] => N 
    [dia] => 1 
    [activo_defecto] => 118.209 
    [reactivo_defecto] => 0 
    [empresa] => Luz Osorno 
    [barra_internal_name] => La Union 13.8 
    [barra_cen_name] => La Union 13.8 
    [barra_cne_name] => L.UNION_______013 
    [barra_cen_name_2] => La Union 1 023 
    [tipo_barra] => SPD 
)

EDIT: the output of print_r($data[0]["fecha"].["date"]);die(); is

2005-11-01 00:00:00Array

I don't know what it means that...

try

$data[0]["fecha"]->formatLocalized('Y');   // 2005
$data[0]["fecha"]->formatLocalized('m');   // 11

EDIT: the output of print_r($data[0]["fecha"].["date"]);die(); is

2005-11-01 00:00:00Array

because you are concatenating $data[0]["fecha"] and ["date"] with the operator '.' and printing it. Internally, is interpreted as:

$data[0]["fecha"]->toString.["date"]->toString

尝试直接从Carbon对象调用:

$str = $data[0]["fecha"]->format('Y m');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM