Updating field datetime sqlsrv

Asked

Viewed 394 times

-2

I need to update the date in the date field, type datetime, in a table, taking today’s date, for example. I’m trying to do it this way:

$dataHoje = new DateTime();

$sql = "UPDATE [RDO].[dbo].[ANALISE_CRITICA] SET
        TXTOBS='$objetoExtra',
        VLRECEITACONT='$receitaContrato',                                                             VLRECEITABRUTA='$receitaBrutaMarco',
        VLISSQN='$percentualIssqn',
        VLBASE='$baseCalculoIssqn',
        VLIMPOSTTOTAL='$valorTotalImpostos',
        VLCOMISSAO='$comissionamento',
        VLCUSTO='$custoDireto',
        VLADMLOCAL='$admLocal',
        VLRISCO='$risco',
        VLCUSTOFIN='$custoFinanceiro',
        VLADMCENTRAL='$admCentral',
        VLRESULTFIN='$resultadoFinanceiro',
        VLCORRETAGENS='$corretagem',
        dataAlteracao = $dataHoje 
      WHERE ID=$id";

$stmt = @sqlsrv_query( $conn, $sql);

However, when I try to update the system I get the following warning: "Catchable fatal error: Object of class Datetime could not be converted to string" What problem is this?

  • 1

    Try to pass the formatted date like this: $dataHoje->format('Y-m-d H:i:s');

  • Where? Right after $dataHoje = new Datetime() or direct in sql command?

  • 1

    Can you get the server’s time date or does it need to be an input via application? DBMS has functions that return server time, getdate() or sysdate() depending on column type

2 answers

3


@Gustavosevero, follow the example of the code, as link

$dataHoje = new DateTime();
$dataHoje = $dataHoje ->format('d/m/Y'); 
echo $dataHoje ;
  • I withdrew the +7 months, the date entered the bank, however with year 1905-06-12... Of course, I changed the format to ('Y-m-d'), also

  • Putting, EXACTLY as you put it here, the date enters 1900-01-01

  • So, I don’t know, man, is it not your machine/server date? Testing here is normal

1

I took the formatted date as string using method format() passing the desired format, remember to quote the value of a date in the update.

$dataHoje = new DateTime();
$dataFormatada = $dataHoje->format('Y-m-d H:i:s'); //formato: 2014-10-22 15:06:11

$sql = "UPDATE ....
          dataAlteracao = '$dataFormatada'
        WHERE ID = $id";

If the date comes from an input entered by the user in the dd/mm/yyyy format use the method createFromFormat() to create a date and then call format() to leave the date in the format accepted by the yyyy-mm-dd.

<?php
$input = '24/10/2014';

$data = DateTime::createFromFormat('d/m/Y', $input);
$dataFormatada = $data->format('Y-m-d');

echo $dataFormatada; //2014-10-24
  • Via same application.

  • @Gustavosevero, I don’t understand

  • Someone had asked me if I was trying to get the server date or what the user log in to via the application, so I answered that via the application, for a <input type="date"...

Browser other questions tagged

You are not signed in. Login or sign up in order to post.