Search code examples
laraveldateunix-timestamp

Problem converting date from a bootstrap datepicker to a different format


Working on an app whereby am capturing some input fields using bootstrap datepicker. Am displaying the format in dd/mm/yy format to the user which works fine. On the backend (build in Laravel PHP), I need to convert it to yy-mm-dd format which is the required format when storing the date field in the API.

In the controller when I dump the data I get 28/01/2019 but when I convert it I get 1970-01-01. What could be the issue?

Markup

<div class="form-line registar love {{ $errors->has('dob') ? ' has-error' : '' }}">
    <input type="text" placeholder="Date of Birth *" class="form-input dateTextBox" name="dob" id="dob" value="{{isset($user->dob) ? $user->dob : old('dob') }}" required>
</div>

Javascript Logic (Bootstrap datpicker)

 var maxBirthdayDate = new Date();
maxBirthdayDate.setFullYear( maxBirthdayDate.getFullYear() - 18 );
maxBirthdayDate.setMonth(11,31);
$( function() {
  $( "#dob" ).datepicker({
    changeMonth: true,
    changeYear: true,
    dateFormat: 'dd/mm/yy',
    maxDate: maxBirthdayDate,
    yearRange: '1900:'+maxBirthdayDate.getFullYear(),
  });
});

Controller Logic

public function validateDate(Request $request){   
        //dd($request->dob);

        //28/02/2019 after dd() above

        //Convert 
        $dobCv = date("Y-d-m", strtotime($request->dob));

        dd($dobCv);

        //1970-01-01 after dd() above
}

Solution

  • You can simply use Carbon :

    $dobCv = Carbon::createFromFormat('d/m/Y', $request->dob)->format('Y-m-d');
    

    And don't forget the import :

    use Carbon\Carbon;