how to retrieve a sql datetime object with a php $row?

13,797
$string=$row["date_column"]->format('Y-m-d H:i:s')
Share:
13,797
not_shitashi
Author by

not_shitashi

Updated on June 04, 2022

Comments

  • not_shitashi
    not_shitashi almost 2 years

    For instance:

    $sql = "SELECT * FROM db";
    $query = sqlsrv_query($conn, $sql);
    
    while($row = sqlsrv_fetch_array($query)){
        echo "$row[date_column]";
    }
    

    will crash

    Most of the answers I've found are assuming you want to order your query by a datetime, but I just want to turn the datetime object into a string after I have all the rows.

    I don't really understand how to use the php date() function, I've tried:

    echo date("m/d/Y",$row[date_column]); //prints nothing
    
  • Ozzah
    Ozzah over 12 years
    Question is asking about MSSQL, not MySQL, but I don't see why this method would not work for both.
  • Gregg
    Gregg over 12 years
    Whoops, your right! But yes, it should if MSSQL stores datetime the same.
  • not_shitashi
    not_shitashi over 12 years
    Hi, thanks for you answer, however, what I am getting from echo date("m/d/Y", strtotime($row["date_column"]); is the date: 12/31/1969 for every entry. Also, that is not the correct date for any of the entries.
  • Gregg
    Gregg over 12 years
    You will get that date when PHP date() is given a bad input value. So I can help you more, can I have a sample of what "echo $row["date_column"];" produces?
  • not_shitashi
    not_shitashi over 12 years
    it returns a datetime object (for the Data Type in sql) and the format is yyyy-mm-dd hh:nn:ss.xxx where n = minutes and x = milliseconds I think.
  • Gregg
    Gregg over 12 years
    That's strange. It works when I try it on my server, with the format you provided. The code I am trying is: "$time = "2001-01-13 10:45:55.123"; echo date("m/d/Y", strtotime($time));" Which produces: "01/13/2001". What do you get when you just try "echo strtotime($row["date_column"]);"?