0

I am having problems with inserting records to mysql. The records I have are from a different website (downloaded records) in .CSV and the dates are in "2/12/2015" format. I learned that PHP or Mysql only accepts or understands "YYYY-MM-DD" format or even "YYYYMMDD".

How can I format the dates before including them in the mysql query string? How can I change or convert the arrangement "2/12/2015" and turn it into "2015-2-12"?

Jin Pards
  • 189
  • 1
  • 2
  • 13

2 Answers2

3

Just use date() and strtotime() functions:

$date = strtotime("2/12/2015");
echo date('Y-m-d', $date);
Gabriel Rodriguez
  • 1,163
  • 10
  • 23
2

Using explicit date formats:

$dateValue = '2/12/2015';
$date = DateTime::createFromFormat( 'd/m/Y', $dateValue );
$dateValue = $date->format( 'Y-m-d' );

$dateValue holds the converted date

William_Wilson
  • 1,244
  • 7
  • 16
  • Thanks William, may I ask what the difference in outcome is between your suggestion and Gabriel's? Please forgive me for saying but if both produce the same output I might go with Gabriel's as it's easier to remember for a noob like me :D – Jin Pards Sep 24 '15 at 17:29
  • The main difference is the date format supplied here vs. letting PHP determine the format and convert to an unix timestamp. strtotime http://php.net/manual/en/function.strtotime.php . Both are accurate implementations given your requirements it is up to you. It is just my preference to define the expected input format in addition to the output and avoid strtotime unless that is the output I desire: http://www.hashbangcode.com/blog/how-i-learned-stop-using-strtotime-and-love-php-datetime – William_Wilson Sep 24 '15 at 17:37
  • I'm sorry but I couldn't figure this out but the date being returned here seem to be different date, the format worked though :( – Jin Pards Sep 29 '15 at 19:10
  • The output is 2015-12-02 which is the same date as the input just in a different format. If there's something you don't understand feel free to start your own topic :) – William_Wilson Sep 30 '15 at 11:19
  • Yes sorry, when I tried it I was using '2/12/2015' and the output I was getting was '2014-4-7'. The format was correct but the date was becoming incorrect. Anyway I will attempt to use this again as it looks more complete – Jin Pards Sep 30 '15 at 16:26