2

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:

  • If input ($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.

user5005768Himadree
  • 1,375
  • 3
  • 23
  • 61
  • 1
    Do a `var_dump($datestring);` please--does it say `"not"` or what does it say? What format would you like the `$date` in? `//` or `//` or what? – Will Jan 24 '16 at 09:47
  • 2
    `1970-01-01` is the date of the `0` unix timestamp (the UNIX Epoch). This usually means that `strtotime()` returned an error. – Will Jan 24 '16 at 09:48
  • Thanks @Will.var_dump($datestring); showing string '24/01/2016' (length=10).thanks – user5005768Himadree Jan 24 '16 at 10:29

3 Answers3

2

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();
www.data-blogger.com
  • 4,076
  • 7
  • 43
  • 65
2

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);     
?>
Sashant Pardeshi
  • 1,075
  • 7
  • 21
1

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.

Drone
  • 1,114
  • 1
  • 12
  • 31