This question already has an answer here:
I am new to PHP. I have a date string from a date-picker input field. But when I try to convert date string it into a date, I get an unexpected date.
Sample error:
$datestamp
) contains 24/01/2016
, then it becomes $date = '70/01/01
[error]Here is the PHP code:
<?php
$datestring = (isset($_POST['datetimepicker1'])) ? $_POST['datetimepicker1'] : "not";
$date = date("y/d/m", strtotime($datestring));
echo $datestring;
echo var_dump($date);
?>
updates: here is my datepicker code
<script type="text/javascript">
$(function () {
$('#datetimepicker1').datetimepicker({format:"DD/MM/YYYY", useCurrent: false });
});
</script>
Please help me fix this. Is this a format problem? I need to insert the date into an Oracle database.
</div>
According to jQuery, the datepicker default format is the following: mm/dd/yy
.
So, you can try this (in order to convert the $datestring
to the y/m/d
format):
<?php
$datestring = '24/01/2016';
list($day, $month, $year) = explode('/', $datestring);
$date = DateTime::createFromFormat('Ymd', $year . $month . $day);
echo $date->format('y/m/d');
?>
You can also change the datepicker:
var date = $('#datepicker').datepicker({ dateFormat: 'dd-mm-yy' }).val();
Use this code
<?php
$datestring = (isset($_POST['datetimepicker1'])) ? $_POST['datetimepicker1'] : "not";
$datestring = str_replace('/', '-', $datestring);
$date = date("y/d/m", strtotime($datestring));
echo $datestring;
echo var_dump($date);
?>
Just replace('/') to ('-') before passing to strtotime function. Sometime ('/') not work.
Please replace date function with below code. I have used explode to extract year, month and date separately, pass it to strtotime function.
<?php
$datestring = (isset($_POST['datetimepicker1'])) ? $_POST['datetimepicker1'] : "not";
$date_arr = explode('/',$datestring);
$date = date("Y/m/d", strtotime($date_arr[2].$date_arr[1].$date_arr[0]));
echo $datestring;
echo var_dump($date);
?>