Php datetime timezone database

date_timezone_set

Устанавливает новый часовой пояс для объекта ( object ) DateTime .

Подобен методу DateTimeImmutable::setTimezone() , за исключением работы с объектом DateTime .

Процедурная версия принимает объект DateTime в качестве первого аргумента.

Список параметров

Только для процедурного стиля: объект DateTime , возвращаемый date_create() . Функция изменяет этот объект.

Объект класса DateTimeZone , представляющий требуемый часовой пояс.

Возвращаемые значения

Возвращает объект DateTime для связывания методов. Лежащий в основе момент времени не изменяется при вызове метода.

Примеры

Пример #1 Пример использования DateTime::setTimeZone()

$date = new DateTime ( ‘2000-01-01’ , new DateTimeZone ( ‘Pacific/Nauru’ ));
echo $date -> format ( ‘Y-m-d H:i:sP’ ) . «\n» ;

$date -> setTimezone (new DateTimeZone ( ‘Pacific/Chatham’ ));
echo $date -> format ( ‘Y-m-d H:i:sP’ ) . «\n» ;
?>

$date = date_create ( ‘2000-01-01’ , timezone_open ( ‘Pacific/Nauru’ ));
echo date_format ( $date , ‘Y-m-d H:i:sP’ ) . «\n» ;

date_timezone_set ( $date , timezone_open ( ‘Pacific/Chatham’ ));
echo date_format ( $date , ‘Y-m-d H:i:sP’ ) . «\n» ;
?>

Результат выполнения данных примеров:

2000-01-01 00:00:00+12:00 2000-01-01 01:45:00+13:45

Смотрите также

  • DateTimeImmutable::setTimezone() — Устанавливает часовой пояс
  • DateTime::getTimezone() — Возвращает часовой пояс относительно текущего значения DateTime
  • DateTimeZone::__construct() — Создаёт новый объект DateTimeZone

User Contributed Notes

Источник

Dates and time zones in PHP

Working on an existing codebase means you can get unexpected surprises, like having dates being represented as strings inside application logic. We decided to migrate this to PHP’s DateTime objects. While migrating some of these string to DateTime instances in our codebase I came across code where we create a DateTime object based on data from our database and from API responses. The time zones of our application and our website are one and the same, but some APIs tend to send their data in UTC. And our default time zone is Europe/Amsterdam. What can possibly go wrong?!

Naive

The code I found used a naive solution. Although it might look good — we add a time zone, right? — the result is not what I expected:

// somewhere in our application bootstrap date_default_timezone_set('Europe/Amsterdam'); // somewhere deep in our application $date = \DateTimeImmutable::createFromFormat( \DateTime::ATOM, '2020-07-23T12:00:00+00:00' ); // let's output print $date->format('c'); 

This will print 2020-07-23T12:00:00+00:00 . Nice! Now let’s show this to our users. Users typically don’t care for time zones, they just want to know what the date and time is for them. You might want to localize this, but for now I will use the format YYYY-MM-DD HH:MM:SS . So what will be the output of $date using this format when in Europe/Amsterdam? 2020-07-23 12:00:00 . Hmmmz, that’s not right. I expected this to be 2020-07-23 14:00:00 , seeing that Amsterdam is in UTC + 2:00. NB I’m using DateTimeImmutable in my examples and not DateTime . This is deliberate. As DateTime objects are mutable by default you can find yourself in unexpected situations. An example is when you pass a DateTime object to a different class or function. You don’t know what this class or function will do with that object and if it decides to use add or sub your instance will be affected:

function getUpcomingOpeningHours(DateTime $start): array  $database->query( '/* query */', [ 'start' => $start, 'end' => $start->add(new DateInterval('P7D')) ] ); > $date = new DateTime(); $openingHours = getUpcomingOpeningHours($date); print "Upcoming opening hours since $format('Y-m-d')>: "; 

Specify a time zone 1

A look at the documentation of DateTime::createFromFormat shows it accepts a third parameter; an instance of DateTimeZone :

// set the default time zone date_default_timezone_set('Europe/Amsterdam'); // create a date object $date = \DateTimeImmutable::createFromFormat( \DateTime::ATOM, '2020-07-23T12:00:00+00:00', new \DateTimeZone(date_default_timezone_get()) ); // show the user print $date->format('Y-m-d H:i:s'); 

The timezone parameter and the current timezone are ignored when the time parameter either contains a UNIX timestamp (e.g. 946684800) or specifies a timezone (e.g. 2010-01-28T15:00:00+02:00).

This means that this approach only works if the date time string you are receiving is set in a specific time zone, but does not have a time zone indication in the date time string. In my personal opinion that is an undesirable situation, but I have seen far worse:

// set the default time zone date_default_timezone_set('Europe/Amsterdam'); // create a date object $date = \DateTimeImmutable::createFromFormat( 'Y-m-d H:i:s', '2020-07-23 12:00:00', new \DateTimeZone(date_default_timezone_get()) ); // show the user print $date->format('Y-m-d H:i:s'); 

This prints 2020-07-23 12:00:00 ; winning! But wait, this example does not make any sense. If you create a DateTime object without any time zone specification it will use the default time zone. What happens if we specify a different time zone?

// set the default time zone date_default_timezone_set('Europe/Amsterdam'); // create a date object $date = \DateTimeImmutable::createFromFormat( 'Y-m-d H:i:s', '2020-07-23 12:00:00', new \DateTimeZone('UTC') ); // show the user print $date->format('Y-m-d H:i:s'); 

Specify a time zone 2

// set the default time zone date_default_timezone_set('Europe/Amsterdam'); // create a date object $date = \DateTimeImmutable::createFromFormat( \DateTime::ATOM, '2020-07-23T12:00:00+00:00' )->setTimeZone(new \DateTimeZone(date_default_timezone_get())); // show the user print $date->format('Y-m-d H:i:s'); 

This will print 2020-07-23 14:00:00 . Which is correct since at July 23rd 2020 Europe/Amsterdam is +02:00 . I’m using the functions date_default_timezone_set() and date_default_timezone_get() . Unless you let your users specify their time zone themselves I would recommend using these functions — or abstractions of them — in your code for this. By consistently using date_default_timezone_get() you make sure your code will not break once it gets decided your application should also become available in territories with a different time zone. You need to make sure that somewhere in the bootstrap of your application you specify the correct time zone, and your entire application should follow you in the time zone migration.

tl;dr

When you’re building DateTime objects from date time strings and you want to use it to display a human readable date time format always specify the time zone of the object by using DateTime::setTimezone() . And to ensure you don’t end up showing incorrect times it is always a good idea to either store or submit a timestamp, which is by definition in UTC — but can only represent dates after the unix epoch, or a date time with a time zone indication.

Источник

PHP Timezones- How to Set/Change Timezone, With Examples

Managing PHP Timezones

This article provides a combined tutorial for the PHP timezone functions, showing how to change the timezone globally or temporarily for a script/object.

Timezones are a huge hassle. If your app has users from around the world, you’ll eventually run into the annoying task of ensuring that date handling works effectively for everyone – including the accuracy of times displayed and the format they are displayed in.

PHP provides several tools to make timezone handling easier, allowing you to set the default timezone for the system, a script, or a specific DateTime object.

PHP DateTime Objects

This article will refer to PHP DateTime objects. These variables contain multiple pieces of information about a given date/time – the time itself and the timezone it is in.

List of Supported Timezones

When setting your timezone, only valid timezone values are allowed (For example, ‘Europe/Amsterdam’). It’s a long list – so rather than reproduce it, here it is in the official PHP docs:

Finding Out What Timezone Will be Used in a PHP Script

To find out what timezone will be used in a script, run the following function anywhere in the script:

date_default_timezone_get()

This function accepts no parameters and will return the timezone used for DateTime objects in the currently running PHP script.

In order of precedence, the timezone to be used is either:

  • The timezone set using date_default_timezone_set()
  • The timezone is configured in the PHP date.timezone ini option (usually via the php.ini configuration file)
  • If neither of the above is properly set, all dates will default to the UTC timezone
echo date_default_timezone_get();

Which will output (obviously with your configured timezone):

Setting the Default Timezone for a Script

The following function will set the timezone for the script it is run in only. It should be used towards the beginning of the script before any DateTime objects are created to be all created with the same default timezone. The syntax is as follows:

date_default_timezone_set ( $timezoneId )

This function accepts a single parameter – a timezone from the list of supported timezones. It would return true if it successfully sets the timezone or false if an invalid timezone was supplied.

date_default_timezone_set('America/Los_Angeles'); echo date_default_timezone_get();

Above, the script’s timezone has been changed, and the change is confirmed using date_default_timezone_get().

The change made by calling this function is not permanent and does not apply to anything outside of the script’s execution.

Setting Timezone for the System Globally in php.ini

If you wish to change the timezone globally in PHP so that the default timezone for all PHP scripts executed on the system is changed, you will need to edit the php.ini file.

Note that it is common for there to be a configuration file for both the CLI (Command Line Interface) and a separate configuration file used by the webserver serving PHP applications (e.g., Apache).

Make sure you change the one you need to change or both. Their location will depend on your system configuration but usually can be found in /etc/php/ on Linux.

date.timezone = "America/Los_Angeles"

You may need to reboot your web server to see the change take effect.

Setting the Timezone for a Specific PHP DateTime Object

Finally, it’s possible to change the timezone for a specific PHP DateTime object.

When created and when otherwise not specified, PHP dates/times are created in the default timezone.

It is possible to specify the timezone while creating a DateTime object by passing it as the second parameter:

$date = new DateTime('2021-01-01', new DateTimeZone('America/Los_Angeles')); echo $date->format('Y-m-d H:i:sP');

It is then possible to change the timezone of an existing DateTime object using the setTimezone() method:

$date->setTimezone(new DateTimeZone('Europe/Amsterdam')); echo $date->format('Y-m-d H:i:sP');

Note that when the timezone is changed, the time is changed – if the time value is 00:00 before the change, it will be different afterward, reflecting the equivalent time in the other timezone.

If you wish to change the timezone but not have the time change stored – check out Carbon PHP below for advanced time handling.

Carbon PHP Makes it Easier

If you are building a complex application, I recommend checking out Carbon.

Carbon extends the PHP DateTime object and provides many tools for handling dates, times, timezones, time differences, converting times from one timezone to another, and more.

It makes life easier and allows you to be more confident that dates/times are being handled correctly for your user, regardless of where they are. Find it at:

Or, if you’re using Laravel – it’s already installed. Laravel has Carbon built-in, and all dates provided through Laravel are already Carbon objects.

Источник

Читайте также:  Html body onload href
Оцените статью