Change date to MySql format

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • code green
    Recognized Expert Top Contributor
    • Mar 2007
    • 1726

    Change date to MySql format

    I know this is simple but I have been using mssql for so long
    I have forgotten how to do it in MySql.

    I am reading a date from a CSV file of the format
    dd/mm/yyyy
    How do I convert this to ISO 8601 standard
    yyyy-mm-dd
    The value is an array element of which I am looping through removing
    spaces and currency symbols and hopefully correcting the date
    Code:
    foreach($row as &$element)
    {
    	$element = trim($element);
        if(strpos($element,'£'))
    	    $element = ltrim(($element),'£');
        if(strpos($element,'date'))
              /*******How do I convert to MySql **************/
    }
  • hoopy
    New Member
    • Feb 2009
    • 88

    #2
    There are quite a few ways to do it, explode it into an array and rebuild it I guess or what about something like this:

    Code:
    $date = "12/05/2009";
    $date = preg_replace("/([0-9]{2})\/([0-9]{2})\/([0-9]{4})/", '$3-$2-$1', $date);
    echo $date;
    Would output:

    Code:
    2009-05-12
    So just use that when you insert into the MySQL Date field?

    Comment

    • code green
      Recognized Expert Top Contributor
      • Mar 2007
      • 1726

      #3
      Thanks for the reply Hoopy.
      But woke up this morning and remembered.
      This is my code
      Code:
      foreach($row as $key=>&$element)
      {
          if(stripos($key,'date')!==false)
              $element = date('Y-m-d',strtotime($element));
      Or 'Y-m-d' could be replaced with 'c' for PHP 5 but this adds an empty time value

      This works for an assoc array where any date element has 'date' as part of the key name

      Comment

      Working...