Reputation: 557
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
}
Upvotes: 3
Views: 1779
Reputation: 2275
You have the problem because forward slash (/) signifies American M/D/Y formatting in strtotime
and in your example 28/02/2019
28 is month. So strtotime
returns false
. I recommend you to use Carbon
library as was said above or change /
with -
if you want your way:
$dobCv = date("Y-d-m", strtotime(str_replace('/', '-', $request->dob)));
Upvotes: 0
Reputation: 862
Why don't you use Laravel build in Carbon
$date = Carbon::createFromFormat('d/m/Y', $date);
Then you can do $date->toDateTimeString();
or whatever you want to do with the Carbon date object
Upvotes: 3
Reputation: 11083
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;
Upvotes: 1
Reputation: 63
Changing input type text into date might help you.
eg: <input type="date" .......>
Upvotes: 0