Object of class DateTime could not be converted to string

后端 未结 7 569
灰色年华
灰色年华 2020-11-27 19:16

I have a table with string values in the format of Friday 20th April 2012 in a field called Film_Release

I am looping through and i want to convert

相关标签:
7条回答
  • 2020-11-27 19:49

    Check to make sure there is a film release date; if the date is missing you will not be able to format on a non-object.

    if ($info['Film_Release']){ //check if the date exists
       $dateFromDB = $info['Film_Release'];
       $newDate = DateTime::createFromFormat("l dS F Y", $dateFromDB);
       $newDate = $newDate->format('d/m/Y'); 
    } else {
       $newDate = "none"; 
    }
    

    or

     $newDate = ($info['Film_Release']) ? DateTime::createFromFormat("l dS F Y", $info['Film_Release'])->format('d/m/Y'): "none" 
    
    0 讨论(0)
  • 2020-11-27 19:57

    Because $newDate is an object of type DateTime, not a string. The documentation is explicit:

    Returns new DateTime object formatted according to the specified format.

    If you want to convert from a string to DateTime back to string to change the format, call DateTime::format at the end to get a formatted string out of your DateTime.

    $newDate = DateTime::createFromFormat("l dS F Y", $dateFromDB);
    $newDate = $newDate->format('d/m/Y'); // for example
    
    0 讨论(0)
  • 2020-11-27 20:01

    It's kind of offtopic, but i come here from googling the same error. For me this error appeared when i was selecting datetime field from mssql database and than using it later in php-script. like this:

    $SQL="SELECT Created
    FROM test_table";
    
    $stmt = sqlsrv_query($con, $SQL);
    if( $stmt === false ) {
        die( print_r( sqlsrv_errors(), true));
    }
    
    $Row = sqlsrv_fetch_array($stmt,SQLSRV_FETCH_ASSOC);
    
    
    $SQL="INSERT INTO another_test_table (datetime_field) VALUES ('".$Row['Created']."')";
    $stmt = sqlsrv_query($con, $SQL);
    if( $stmt === false ) {
        die( print_r( sqlsrv_errors(), true));
    }
    

    the INSERT statement was giving error: Object of class DateTime could not be converted to string

    I realized that you CAN'T just select the datetime from database:

    SELECT Created FROM test_table
    

    BUT you have to use CONVERT for this field:

    SELECT CONVERT(varchar(24),Created) as Created FROM test_table
    
    0 讨论(0)
  • 2020-11-27 20:03

    If you are using Twig templates for Symfony, you can use the classic {{object.date_attribute.format('d/m/Y')}} to obtain the desired formatted date.

    0 讨论(0)
  • 2020-11-27 20:04

    Try this:

    $Date = $row['valdate']->format('d/m/Y'); // the result will 01/12/2015
    

    NOTE: $row['valdate'] its a value date in the database

    0 讨论(0)
  • 2020-11-27 20:08

    You're trying to insert $newdate into your db. You need to convert it to a string first. Use the DateTime::format method to convert back to a string.

    0 讨论(0)
提交回复
热议问题