Adjust time in PHP string

Asked

Viewed 599 times

2

My hosting is configured for UTC (GMT 00:00) and I can’t change through Mysql, due to blocks being a shared host. My PHP code brings results of date/time of orders, but it is with 3h above (due to our GMT of Sao Paulo be -03:00)

I have this function and I would like to correct in it this difference of -3 hours.

function converteDataHora($data, $hora=true){
    // Aqui pegamos a data, e dividimos ela em duas, usando a métodoExplode()
    $data = explode(" ", $data);

    // AQUI TEMOS AS DUAS PARTES
    $data1 = $data[0]; // DATA (xxxx-xx-xx)
    $data2 = $data[1]; // HORA (xx:xx:xx)

    // Agora dividimos a data em três partes, também usando o método Explode()
    $data1 = explode("-", $data1);

    $dia = $data1[2]; // Retorna o dia
    $mes = $data1[1]; // Retorna o mês
    $ano = $data1[0]; // Retorna o ano

    /* Como deve ter notado, dentro das variáveis existem o número de array, o 0(zero) trás o ano, 1 o mês e o 2 o dia para saber mais recomendo pesquisar sobre a função

    Agora vamos formatar a data, trazemos as strings, e a hora
    Aonde dia traz a string $data1[2]
    Aonde mês traz a string $data1[1]
    Aonde ano traz a string $data1[0]

    Como não precisamos "explodir" a hora trazemos ela normalmente através da string $data2

    */

    $data = $dia . "/" . $mes . "/" . $ano;

    if($hora==true)
        $data .=  " às " . $data2;

    // Retornamos o valor
    return $data;
}

3 answers

3

Simply always severe (INSERT INTO, UPDATE, REPLACE) as UTC, so it’s great that your bank is UTC, because if you change the region system or even change the country and the times are as America/Sao_Paulo or else the system will "break".

Anytime READ the bank lines you make up the time, because any time is based on GMT or UTC and so just adjust the time zone in PHP, as suggested in the other reply, but whenever it is updating in the random bank is a manual time you will have to convert the date and time to UTC (at the time of recording).

To write to the database (if you write manually instead of using the mysql functions) because the value comes from a form you can do something like (code hypothetical):

$horario = gmdate('Y-m-d H:i:s', strtotime($_POST['horario_selecionado_pelo_usuario']);

$stmt = $mysqli->prepare('INSERT INTO exemplo (horario) VALUES (?)');

$stmt->bind_param('s', $horario);

$stmt->execute();

Date functions with prefix gm work in GMT/UTC format (according to documentation https://www.php.net/manual/en/function.gmdate.php) and this way you do not need to adjust when recording, use the date_default_timezone_set only to display, passing the time values in the bank with date(), without the prefix gm:

if (!$stmt->bind_result($id, $horario)) {

    while ($stmt->fetch()) {
        echo 'ID: ', $id, '<br>';
        echo 'Horário: ', date('d/m/Y h:i', strtotime(horario)), '<br>';
    }

}

The hypothetical codes used are based on the mysqli API and not the PDO, but it is easy to adapt, if you have any error or even exaggeration in the codes communicate me, because at the time I could not test


By the way, I must say that forcibly setting up a time zone can be somewhat complicated, if the system is small all right, but if it is a company or a website accessed by several states of the country it would be better to adjust the Timezone according to the user’s region (of course this is more complicated)

  • This way did not give, because I put an echo inside the page that makes the save, and there it updates the time, but when saved in mysql, it records as GMT date 0 (3h ahead)

  • Dear @Evertonthomazi you probably set up something wrong or failed to apply the suggested logic in the reply, can give more details?

  • This which I found strange, because I put <?php date_default_timezone_set("America/Sao_paulo"); ? > in the config.php of my site, in the php of the cart (that makes the request), and I put an "echo date('H:i:s')" to see the time, when I changed the Timezone to another random, this echo changed, but in recording the request, it still saved as UTC

  • @Evertonthomazi depends on how you are recording

  • @Evertonthomazi Sorry, it was really my mess, I set the example $horario = gmdate('Y-m-d H:i:s', strtotime($_POST['horario_selecionado_pelo_usuario']);

1

0

I managed to solve by doing the following, in MYSQL the 'date' column was set with "current_timestamp()", then I left NULL and started sending the date on my website as follows > $data["date"] = date('Y-m-d TH:i:s'); which is the format I need (YYYY-MM-DD HH:II:SS) / (YYYY-MM-DD HH:MM:SS)

Browser other questions tagged

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