Logo

dev-resources.site

for different kinds of informations.

Avoid this when using Date/Time functions in PHP

Published at
8/28/2021
Categories
timezone
php
datetime
Author
rezende79
Categories
3 categories in total
timezone
open
php
open
datetime
open
Author
9 person written this
rezende79
open
Avoid this when using Date/Time functions in PHP

Is there any difference between getting the current date/time in the following ways in PHP?

(new \DateTimeImmutable())->format('Y-m-d H:i:s');
Enter fullscreen mode Exit fullscreen mode
\DateTimeImmutable::createFromFormat('U', (string) time())
    ->format('Y-m-d H:i:s');
Enter fullscreen mode Exit fullscreen mode

Imagine that you are inserting data into a database table using the first way, but when querying the same database table you use the second option.

While the first option will return the current date/time of your server taking into account its Time Zone configuration, the second way will return the current date/time of your server based on UTC time zone.

After creating just a single user into a users table with this data

$user->name = 'Sebastian';
$user->createdAt = (new \DateTimeImmutable())
    ->format('Y-m-d H:i:s');
Enter fullscreen mode Exit fullscreen mode

and querying the user table in this way

$dql = <<<EOT
        SELECT u FROM App\Entity\User u
        WHERE u.createdAt <= :createdAt
    EOT;

$now = \DateTimeImmutable::createFromFormat('U', (string) time())
    ->format('Y-m-d H:i:s');

$users = $this->entityManager()
    ->createQuery($dql)
    ->setParameter('createdAt', $now)
    ->getResult();
Enter fullscreen mode Exit fullscreen mode

you will receive an empty array of $users if the server which hosts your application is located in any country with Time Zone configuration greater than 0 (Austria, Denmark, Germany, and so on).

It will happen because the data which will be inserted into your user table will have the createdAt field filled with 18:14 while when you will try to query the database, you will use the time 16:14.

You didn't create any user before 16:14!

You will never find the users that you have recently created.

It occurs because when you use U to format the date/time values, you get a Unix Timestamp date/time format which gets the date/time always based on Coordinated Universal Time, and never takes into account the Server's Time Zone configuration.

This concept looks pretty basic, but maybe you have never had this issue because you have been working bellow UTC Time Zone (Denmark, South America, Canada, USA, and so on).

Pay attention to that, and you will never suffer trying to solve this issue.

timezone Article's
30 articles in total
Favicon
Converting date by user time zone in "NestJS", and entering and displaying date in "Angular"
Favicon
Timezone support in a full-stack application based on NestJS and Angular: working with REST and WebSockets
Favicon
Python: it is now() time to migrate from utcnow()
Favicon
geo2tz - 4 years later
Favicon
🌐 How to Change Time Zone in Google Chrome to Test Different Timezones
Favicon
¿Cómo trabajar correctamente con fechas?
Favicon
How to fix Dynamics AX 2012 R3 when the time is 1 hour ahead when not using daylight savings time
Favicon
Config Timezone Laravel in Your Project
Favicon
Javascript Zoned-Date library - fully DST support
Favicon
ChronoMate: Your Ultimate Time Zone Companion for Seamless Productivity and Scheduling Ease!
Favicon
supabase timezone + cron
Favicon
Command Prompt - Set Timezone
Favicon
Troubleshooting Timezone Issues in PostgreSQL with DBeaver
Favicon
Fixed: WHM (CPanel) + Laravel Timezone Issue
Favicon
Solve UK time changes (DST) with NodeJS and date-fns and Docker (epoch/unix format)
Favicon
Is there any reason to use ZoneId.of("UTC") instead of ZoneOffset.UTC?
Favicon
Debugging timezone issue in Java [Linux]
Favicon
Local time of employees in Notion
Favicon
Modificando a hora nas configurações do PHP8
Favicon
Time change in daylight saving
Favicon
Avoid this when using Date/Time functions in PHP
Favicon
Timezone for DateTime Field at Laravel Nova
Favicon
NTP (Network Time Protocol) Setup for Linux (Ubuntu) Server
Favicon
[Phoenix LiveView] formatting date/time with local time zone
Favicon
Shift the TZ for your K8s CronJobs
Favicon
Datetimes Are Hard: Part 2 - Writing and running code
Favicon
Where does GMT-0456 Timezone Come From?
Favicon
Dealing with Timezone in JavaScript
Favicon
Date and time gotchas
Favicon
How to avoid and debug most of timezone problems in production

Featured ones: