John Davidson

laravel - PHP date change strtotime does not work well

0 comments
Message:


Date doesn't change the format(YYYYMM -> YYYYY-MM) correctly.


I would like to get YYYYMM (int) changed YYYY-MM to use HTML month input


I implemented like this... but $s_month always displays 2021-06 somehow


                {{$test->month }}//202005
@php
$s_month= $test->month ? date('Y-m',strtotime($test-> month)):"";
@endphp
{{$s_month}} // it displays 2021-06
<input name="s_month" type="month" value="{{$s_month?? ''}}"></input>


My Answer:
The issue here is with the format of the date string that you are passing to the strtotime function. The strtotime function expects the date string to be in a specific format in order to correctly parse it.

In your case, the date string `$test->month` is in the format 'YYYYMM' (e.g. '202005'), which is not a standard date format that strtotime can parse correctly.

To fix this issue, you can first convert the 'YYYYMM' format to 'YYYY-MM' format before passing it to the strtotime function. Here's how you can do it:

php
{{$test->month }} // 202005
@php
$year = substr($test->month, 0, 4);
$month = substr($test->month, 4, 2);
$dateString = $year . '-' . $month;
$s_month = $test->month ? date('Y-m', strtotime($dateString)) : "";
@endphp
{{$s_month}} // it should display the correct formatted date now



By converting the date string to 'YYYY-MM' format before passing it to strtotime, you should be able to correctly parse the date and display it in the desired format in the HTML month input.

Rate this post

3 of 5 based on 3926 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us