0

I have a column in my table named expiry which has type VARCHAR. In the column, there is a mixture of date format like YYYY-MM-DD and MM-DD-YYYY.

How can i re-arrange the format MM-DD-YYYY to YYYY-MM-DD in my laravel view blade ?

View

 @foreach($product_select as $key => $product)
   <tr>
   <td>{{$product->name}}</td>
   <td>{{\Carbon\Carbon::parse($product->expiry)->isoFormat('YYYY MM DD')}}</td>
   </tr>
   @endforeach

In the view above, it throws an error

Could not parse '02-27-2021': DateTime::__construct(): Failed to parse time string (02-27-2021) at position 0

How can i solve this ?

Product Output

{#3504 ▼
  +"product_id": "999"
  +"id": 999
  +"name": "CONFIDO    CONFIDO TABS 60'S HIMALAYA"
  +"code": "P935"
  +"expiry": "03-31-2023"
  +"type": "standard"
}
3
  • @Droid, i have updated the question with the output Commented Mar 9, 2021 at 10:27
  • Well, Carbon can't exactly guess on whether or not you use one format or the other. You'd have to be explicit or convert the formats to something parsable. Commented Mar 9, 2021 at 10:27
  • Try this{{ \Carbon\Carbon::createFromFormat('m-d-Y', $product->expiry')->Format('Y m d')}} Commented Mar 9, 2021 at 10:29

4 Answers 4

4

I'm actually going to just suggest that you stop storing date information in a text varchar column. Instead, you should be using a proper MySQL date column. Here is how you can rectify the situation from MySQL:

ALTER TABLE product ADD COLUMN new_expiry DATE;

UPDATE product
SET new_expiry = CASE WHEN expiry REGEXP '^[0-9]{4}-[0-9]{2}-[0-9]{2}$'
                      THEN CAST(expiry AS DATE)
                      ELSE STR_TO_DATE(expiry, '%m-%d-%Y') END;

ALTER TABLE product DROP COLUMN expiry;
ALTER TABLE product RENAME COLUMN new_expiry TO expiry;

I wouldn't even bother trying to manage this column from Laravel. Even if someone gives you an answer, it will be ugly and a lot of work, and also not best practice.

Sign up to request clarification or add additional context in comments.

Comments

0

try using this

{{ \Carbon\Carbon::parse($product->expiry)->format('YYYY MM DD')}}

1 Comment

Please add some explanation to your answer such that others can learn from it
0

first provide current format

{{ \Carbon\Carbon::createFromFormat("m-d-Y", $product->expiry)->toDateString(); 

Comments

0

you this if your date string is m-d-Y format

else update varchar to date in mysql as @tim-biegeleisen mentioned use that

{{ \Carbon\Carbon::createFromFormat('m-d-Y', $product->expiry')->isoFormat('YYYY MM DD')}}

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.