Obtener la hora UTC en PHP

Habdul Hazeez 20 junio 2023
  1. Utilice gmdate() para obtener la hora UTC
  2. Utilice strtotime() para obtener la hora UTC
  3. Use fecha () para obtener la hora UTC
  4. Utilice date_default_timezone_set() para obtener la hora UTC
  5. Use el objeto DateTime para obtener la hora UTC
Obtener la hora UTC en PHP

Este artículo le enseña cómo obtener UTC en PHP usando cinco métodos. Estos métodos utilizarán date_default_timezone_set(), gmdate(), strtotime(), date() y el objeto DateTime.

Utilice gmdate() para obtener la hora UTC

La función gmdate() formateará una fecha y hora en UTC. Una vez que proporcione gmdate() con su formato de fecha y hora, p. Y-m-d H:i:s, lo mostrará en UTC.

Hemos establecido la zona horaria actual en el siguiente código en Detroit, Michigan. Esto mostrará la hora en Detroit y cómo es en UTC.

Código de ejemplo:

<?php
    // Use the time in Detroit, Michigan, as the default
    // time.
    date_default_timezone_set("America/Detroit");

    // We get the current time in Detroit, Michigan.
    $time_in_Detroit = date('Y-m-d H:i:s', time());

    // We get the UTC time using the gmdate() function
    $utc_time = gmdate("Y-m-d  H:i:s");

    // For comparison, we show the time in Detroit and
    // what it'll be in UTC.
    echo "The current time in Detroit is: " . $time_in_Detroit . PHP_EOL;
    echo "The UTC is: " . $utc_time;
?>

Salida (tendrá resultados diferentes):

The current time in Detroit is: 2022-07-27 17:32:36
The UTC is: 2022-07-27  21:32:36

Utilice strtotime() para obtener la hora UTC

El método strtotime() analizará una fecha y hora textual en una marca de tiempo de Unix. Después de eso, puedes hacer lo que quieras con la marca de tiempo.

En el siguiente código, obtenemos una marca de tiempo de strtotime() usando gmdate(). Luego pasamos la marca de tiempo como segundo parámetro de la función fecha().

Hacer esto le permite escribir su formato de fecha y obtener el resultado en UTC. A modo de comparación, hemos establecido la zona horaria del script en Guatemala.

Código de ejemplo:

<?php
    // Use the time in Guatemala as the default
    // time.
    date_default_timezone_set("America/Guatemala");

    // We get the current time in Guatemala
    $time_in_Guatemala = date('Y-m-d H:i:s', time());

    // We get the UTC UNIX timestamp
    $utc_timestamp = strtotime(gmdate("M d Y H:i:s"));

    // We convert the UNIX timestamp to UTC
    $utc_time = date('Y-m-d H:i:s', $utc_timestamp);

    // For comparison, we show the time in Guatemala
    // and what it'll be in UTC.
    echo "The time in Guatemala is: " . $time_in_Guatemala . PHP_EOL;
    echo "The UTC is: " . $utc_time;
?>

Salida (tendrá resultados diferentes):

The time in Guatemala is: 2022-07-27 15:48:01
The UTC is: 2022-07-27 21:48:01

Use fecha () para obtener la hora UTC

Usaremos la función fecha() para formatear una fecha, pero con algunas matemáticas, fecha() devolverá el UTC. Las matemáticas implican restar el desplazamiento de la zona horaria de la hora de la época, y luego pasa el resultado como el segundo parámetro de la función date().

A modo de comparación, hemos cambiado la zona horaria a Adelaide, Australia. Cuando ejecute el código a continuación, verá el UTC y cómo es en Adelaide.

Código de ejemplo:

 <?php
    // Use the time in Adelaide, Australia, as the default
    // time.
    date_default_timezone_set("Australia/Adelaide");

    // We get the current time in Adelaide
    $time_in_Adelaide = date('Y-m-d H:i:s', time());

    // We get the UTC time using the date() function.
    $utc_time = date("Y-m-d H:i:s", time() - date("Z"));

    // For comparison, we show the time in Adelaide
    // and what it'll be in UTC.
    echo "The time in Adelaide is: " . $time_in_Adelaide . PHP_EOL;
    echo "The UTC is: " . $utc_time;
?>

Salida (tendrá resultados diferentes):

The time in Adelaide is: 2022-07-28 07:56:31
The UTC is: 2022-07-27 22:26:31

Utilice date_default_timezone_set() para obtener la hora UTC

La función date_default_timezone_set() se utiliza para cambiar la zona horaria. También podemos usarlo para devolver el UTC cambiando su parámetro a UTC.

Como resultado, siempre estará en UTC, independientemente de la hora en el script PHP.

<?php
    // Set the default time zone to UTC and all
    // date and time of the current PHP script will
    // be in UTC.
    date_default_timezone_set("UTC");

    // As usual, get the date, but this time, it'll
    // return the time in UTC. That's because this script
    // has its time zone set to UTC.
    $utc_time = date('Y-m-d H:i:s', time());
    echo "The UTC is: " . $utc_time;
?>

Salida (tendrá resultados diferentes):

The UTC is: 2022-07-27 22:36:02

Use el objeto DateTime para obtener la hora UTC

Una combinación del objeto DateTime y el objeto DateTimeZone puede devolver el UTC. Para devolver el UTC, establezca el primer y segundo parámetro de DateTime en ahora y nueva \DateTimeZone("UTC"), y luego puede mostrar el resultado en formato RFC 850.

Código de ejemplo:

<?php
    // Get the UTC using the DateTime object.
    // Its first parameter should be the
    // string "now". And its second parameter should
    // be a new DateTimeZone object and its parameter
    // should be the string "UTC".
    $utc_time = new \DateTime("now", new \DateTimeZone("UTC"));

    // Format the date to show it's a UTC date
    // A sample output is: Wednesday, 27-Jul-22 15:02:41 UTC
    echo $utc_time->format(\DateTime::RFC850);
?>

Salida (tendrá resultados diferentes):

Wednesday, 27-Jul-22 23:00:42 UTC
Habdul Hazeez avatar Habdul Hazeez avatar

Habdul Hazeez is a technical writer with amazing research skills. He can connect the dots, and make sense of data that are scattered across different media.

LinkedIn

Artículo relacionado - PHP Time