0

Basically I have a date a user selects, that is formatted as follows:

01-12-2013 (dd-mm-yyyy)

And I need to format it into a yyyy-mm-dd format for the DB as its a date type like this:

2013-12-01

I store my date in a variable, lets call it $date

I have tried using the createFromFormat function like this:

$processdate = DateTime::createFromFormat('dd-mm-yy', $date);
echo $processdate->format('yy-mm-dd');

But I get an error saying that:

Fatal error: Call to a member function format() on a non-object

Can someone tell me how I am not using it correctly please?

echo_Me
  • 37,078
  • 5
  • 58
  • 78
Bohdi
  • 1,295
  • 4
  • 28
  • 62
  • 1
    you can refer this link http://stackoverflow.com/questions/2487921/convert-date-format-yyyy-mm-dd-dd-mm-yyyy – ajay Mar 06 '13 at 13:32

4 Answers4

2

createFromFormat is documented to return false on failure, which is exactly what happens here. The program blows up when you try to call format on false, which doesn't make any sense.

The reason for this is that your format string is wrong. For the given input, the correct format string is "d-m-Y" (format strings are also documented on the same page).

Of course this means that your output format string is wrong as well: it should be "Y-m-d".

Jon
  • 428,835
  • 81
  • 738
  • 806
1

MySQL can do that for you with the STR_TO_DATE function:

SELECT STR_TO_DATE('01-05-2013','%d-%m-%Y');
Bart Friederichs
  • 33,050
  • 15
  • 95
  • 195
0

this is what i use for converting to and from SQL dates

function human_date_to_sql($date) {
  if($date == '') return '';

  if(stristr($date, "-")) return $date;

  $date_parts = explode('/', $date);
  $sql_date = $date_parts[2] . "-" . $date_parts[1] . "-" . $date_parts[0];

  return $sql_date;
}

function sql_date_to_human($date) {
  if($date == '') return '';

  if(stristr($date, "/")) return $date;

  $date_parts = explode('-', $date);
  $human_date = $date_parts[2] . "/" . $date_parts[1] . "/" . $date_parts[0];

  return $human_date;
}
bizzehdee
  • 20,289
  • 11
  • 46
  • 76
  • 1
    Really? That's a relatively naive approach. Why not use the built in date libraries? What if you want to format your dates differently for human output? These functions already exist in PHP - why rewrite them – Colin M Mar 06 '13 at 13:33
  • They also exist in MySQL. – Bart Friederichs Mar 06 '13 at 13:33
  • @ColinMorelli, were originally needed to do a lot of other things, and then eventually boiled down to these 2 functions. didnt know about `STR_TO_DATE` though, will check that out in future – bizzehdee Mar 06 '13 at 13:36
0

try this:

    function dateInsert($Date, $In = '-', $Out = '-')
        {
            if ($Date)
                return implode($Out, array_reverse(explode($In, $Date)));
            else {
                return false;
            }
        }
$date = '01-12-2013';
echo dateInsert($date);

you can change your date using this function. Hope this will help.

Kabir
  • 2,126
  • 5
  • 21
  • 24