How can DateTime objects be used for date and time formatting in PHP when working with MSSQL?

When working with MSSQL in PHP, DateTime objects can be used for date and time formatting by converting MSSQL datetime values to PHP DateTime objects. This allows for easy manipulation and formatting of dates and times using PHP's built-in DateTime methods.

// Connect to MSSQL database
$serverName = "serverName";
$connectionOptions = array(
    "Database" => "dbName",
    "Uid" => "username",
    "PWD" => "password"
);
$conn = sqlsrv_connect($serverName, $connectionOptions);

// Query MSSQL database
$query = "SELECT date_column FROM table_name";
$result = sqlsrv_query($conn, $query);

// Fetch and format date using DateTime object
while ($row = sqlsrv_fetch_array($result, SQLSRV_FETCH_ASSOC)) {
    $date = $row['date_column'];
    $dateTime = new DateTime($date->format('Y-m-d H:i:s'));
    echo $dateTime->format('Y-m-d H:i:s') . "<br>";
}

// Close MSSQL connection
sqlsrv_close($conn);