Search code examples
datetimelaravel-5php-carbonarray-map

Why carbon helper not working and giving date-time error?


This application built in Lavavel 5. I had a table with day, month and year of birth value. I query the table using this query:

  $tarikh = DB::table('itemregistrations')
            ->select('itemregistrations.lahir_dd', 'itemregistrations.lahir_mm', 'itemregistrations.lahir_yy')
            ->get();

dd($tarikh); produce this output:

Collection {#709 ▼
#items: array:1123 [▼
0 => {#681 ▼
  +"lahir_dd": 9
  +"lahir_mm": "June"
  +"lahir_yy": 1979
}
1 => {#670 ▶}
2 => {#680 ▶}
3 => {#713 ▶}

I want to calculate the age using carbon and insert into the collection as age using array map:

 $tarikh->map(function ($detail) {
        $detail->age = \Carbon\Carbon::parse($detail->lahir_yy)->diffInYears();
        return $detail;
    }); 

But this error appear:

 DateTime::__construct(): Failed to parse time string (0) at position 0 (0): Unexpected character

it is highlighting this code:

  parent::__construct($time, $timezone);
    if (isset($locale)) {
        setlocale(LC_NUMERIC, $locale);
    }

A friend had helped me using this fiddle and works fine ..but in the application, the error appear.

 https://implode.io/i1GanD

Does anybody knows what is the cause of this conflict error? Tried to search on the same problem but still no solution. Thanks


Solution

  • The error had been erased by changing the code to:

     $tarikh->map(function ($detail) {
    
            $detail->Umur = \Carbon\Carbon::createFromFormat('Y',$detail->lahir_yy)->diffInYears(); 
            return $detail;
        });