0

I've searched many questions, but every solution I tried, failed.

Basically, I get a string, for example: "1994-10-29" I have a Date field inside my SQL database. I want to convert this to a Date but when I do, I always get 1970-01-01 which indicates the conversion failed.

My code:

    $date = $_GET["age"];
    $dob = strtotime($date);
    $date_of_birth = date('Y-m-d', $dob);

This is where it goes wrong. I've echo'd the $date and I get the right string from it. The INSERT statement after it also works, since I've tried it with a handpicked date.

I also read a solution where they user str_replace, tried replacing the '-' in my string with '/' but still didn't work.

Hope someone can help me out!

Djorren
  • 21
  • 3

2 Answers2

0

try this:

<?php
     $date = DateTime::createFromFormat('j-M-Y', '15-Feb-2009');
     echo $date->format('Y-m-d');
?>

Reference: http://php.net/manual/de/datetime.createfromformat.php

I hope this is what you are looking for :)

Tobias Schäfer
  • 1,330
  • 2
  • 17
  • 35
0

Looks like your $_GET['age'] variable does not have a valid date string. Here is the specification for strtotime()

http://php.net/manual/en/function.strtotime.php

Here are the valid formats:

http://php.net/manual/en/datetime.formats.php

Ensure the string inside $_GET['age'] is in the correct format.

When you insert into SQL, it's probably in "Y-m-d H:i:s" format, ensure what you are inserting is in this format.

Echo the variable you are inserting. Is it the actual $date variable? If so! Then you want to reformat that $date variable!

Paul Carlton
  • 2,785
  • 2
  • 24
  • 42
  • But in my database the field has Date as type, not Datetime, since it's for your date of birth. So I don't think i need time as well as date? – Djorren Nov 25 '15 at 18:50
  • @Djorren - ah ok, well whatever format, make sure it's in the correct format going into your database and that the string being translated by `strtotime` is correct by datetime.formats link I gave you. It's most likely a date conversion issue you are having. Are you sure that the data in `$_GET['age']` is ALWAYS in the same format coming in? Check for these things. – Paul Carlton Nov 25 '15 at 22:04