php datetime set timezone

DateTime::setTimezone

(PHP 5 >= 5.2.0, PHP 7, PHP 8)

Описание

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

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

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

Примеры

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

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

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

User Contributed Notes 6 notes

In response to the other comments expressing surprise that changing the timezone does not affect the timestamp:

A UNIX timestamp is defined as the number of seconds that have elapsed since 00:00:00 (UTC), Thursday, 1 January 1970.

So: with respect to UTC. Always.

Calling setTimezone() never changes the actual «absolute», underlying, moment-in-time itself. It only changes the timezone you wish to «view» that moment «from». Consider the following:

The timestamp value represented by the DateTime object is not modified when you set the timezone using this method. Only the timezone, and thus the resulting display formatting, is affected.

This can be seen using the following test code:
= new DateTimeZone ( ‘America/Denver’ );
$ESTTZ = new DateTimeZone ( ‘America/New_York’ );

= new DateTimeZone ( ‘America/Denver’ );
$ESTTZ = new DateTimeZone ( ‘America/New_York’ );

It appears that what forzi at mail333 dot com said is correct.

In any case, other output values from format() seem to be accurate, and the true timestamp is always accessible via getTimestamp().

I found unexpected behaviour when passing a timestamp.
timezone seems to always be GMT+0000 unless setTimezone() is set.

= new DateTimeZone ( ‘America/Denver’ );
$ts = 1336476757 ;

/** Output:
string(8) «GMT+0000»
string(10) «1336476757»
string(3) «MDT»
string(10) «1336476757»
**/

Источник

The DateTimeZone class

(PHP 5 >= 5.2.0, PHP 7, PHP 8)

Introduction

Representation of time zone.

Class synopsis

Predefined Constants

DateTimeZone::AMERICA

America time zones.

DateTimeZone::ANTARCTICA

Antarctica time zones.

DateTimeZone::ARCTIC

DateTimeZone::ASIA

DateTimeZone::ATLANTIC

Atlantic time zones.

DateTimeZone::AUSTRALIA

Australia time zones.

DateTimeZone::EUROPE

DateTimeZone::INDIAN

DateTimeZone::PACIFIC

Pacific time zones.

DateTimeZone::UTC

DateTimeZone::ALL

DateTimeZone::ALL_WITH_BC

All time zones including backwards compatible.

DateTimeZone::PER_COUNTRY

Time zones per country.

Table of Contents

User Contributed Notes 2 notes

Seems like a significant differences between php 5.3 and 5.6:

It seems like as of PHP 5.5, creating a new DateTimeZone with a string like ‘EDT’ will cause DateTimeZone::getName() to return ‘EDT’ whereas prior to 5.5 it would convert it would have returned ‘America/New_York’

This is of particular note when using a DateTimeZone object to change the timezone on a DateTime object. Using a DateTimeZone object when set as shown above will cause the conversion to be wrong without throwing any errors.

Источник

date_default_timezone_set

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

date_default_timezone_set — Устанавливает часовой пояс по умолчанию для всех функций даты/времени в скрипте

Описание

date_default_timezone_set() устанавливает часовой пояс по умолчанию для всех функций даты/времени в скрипте.

Вместо использования этой функции, вы можете воспользоваться INI-настройкой date.timezone для установки часового пояса по умолчанию.

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

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

Примеры

Пример #1 Получение часового пояса по умолчанию

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

User Contributed Notes 22 notes

// On many systems (Mac, for instance) «/etc/localtime» is a symlink
// to the file with the timezone info
if ( is_link ( «/etc/localtime» )) <

// If it is, that file’s name is actually the «Olsen» format timezone
$filename = readlink ( «/etc/localtime» );

Yes, I know it doesn’t work on Windows. Neither do I 🙂 Perhaps someone wants to add that functionality.

Hope this helps someone.

As Christopher Kramer said 9 years ago, not setting default timezone has performance impacts on PHP 5.6, and on PHP 7.1

It hasn’t on php 7.2 anymore.

As I set error_reporting to 0 in my script, it doesn’t seem linked to the fact it is logging the error.

I ran its benchmark script (modified) on Linux multiple times, alternating ‘on’ and ‘off’ setting :

This creates a huge problem for downloadable programs, which obviously cannot be hardcoded as this suggests, since the coder has no idea where they will be run.

Seems to me that if the server’s timezone cannot be relied on, then THAT is the the problem which needs fixed. Not, cause the coder’s syntactically-correct work to generate bogus error messages.

You should always turn on notices and have a customer error handler that converts notices or indeed any PHP message to exceptions.

I’ve been doing this for years and it looks like expanding the use of exceptions in PHP itself is an ongoing process. It’s almost certainly stuck with notices from legacy patterns prior to PHP possessing exception capability with the reason it’s not been thoroughly applied being BC breakage.

Similar for asserts, json, etc, etc it all to use exceptions.

Another note. I profiled my PHP script and it reported that calling this function took half the time. Anyone else got this? Is it really that expensive? Am I doubling init time not having it in php.ini and possibly setting to the timezone it’s already on? Or is it messing with time and breaking the time measurement? One day I’ll bother to wrap it in microtime to try to see.

After poundering and knocking my head on the table, I finally got a proper fix for Windows and PHP timezone handling.

Since Windows applies the DST to ActiveTimeBias in the registry, you only need this to apply.
The only problem is, that it cant use the timezone_set command.

You can request a response back in any date-format you wish, or use the default one given in the function itself.

If you want users to choose their own timezones, here’s some code that gets all available timezones but only uses one city for each possible value:

I experienced that using this function highly increases performance of functions like getdate() or date() using PHP 5.2.6 on Windows.
I experienced similar results on Linux servers with PHP 5.2.6 and 5.2.10, although the difference was not that significant on these servers: The PHP 5.2.10 server did run with date_default_timezone_set («only») twice as fast as without. The 5.2.6 server did 5 times faster with date_default_timezone_set. As you can see below, the 5.2.6-Windows machine did a LOT faster.
Of course these machines have completely different hardware and can not really be compared, but all show improved performance.

I checked PHP 4.4.9 on Windows (without date_default_timezone_set of course) and noticed that its as fast as PHP 5.2.6 with date_default_timezone_set.

The following script shows this:

# uncomment to see difference
# date_default_timezone_set(date_default_timezone_get());

// With date_default_timezone_set(): «Time: 0.379343986511»
// Without date_default_timezone_set(): «Time: 7.4971370697»

?>

Note that the timezone is not changed, it is only set again. I really wonder why this makes such a big performance difference, but its good to know.

I found a need to change the timezone based on a DB record, so it would display properly for each record. So I wrapped some of the other posts into this small class:

Note that there may be some unexpected side-effects that result from using either set_default_timezone() or the putenv(«TZ=. «) workalike for earlier PHP versions. ANY date formatted and output either by PHP or its apache host process will be unconditionally expressed in that timezone.

This does indeed include the web server’s logs and other output files and reports which by default usually do not include any indication of timezone. This has a further side-effect on log processing and analysis, obviously.

date() [function.date]: It is not safe to rely on the system’s timezone settings. Please use the date.timezone setting, the TZ environment variable or the date_default_timezone_set() function. In case you used any of those methods and you are still getting this warning, you most likely misspelled the timezone identifier. We selected ‘America/Los_Angeles’ for ‘PST/-8.0/no DST’ instead

Of course this is a problem that recently surfaced since PHP5. Quick fix is to set your time zone, add this line to your php code:

I was having major issues with the date.timezone setting after I updated from 5.3.3 to 5.4.29. I still need to update further, and perhaps it’s a bug in this version that will be fixed when I update..

«php_value date.timezone America/Denver»

And now the timezone is set in any directory I browse in. Very strange, and I still haven’t figured out why It wont work from the php.ini file. But here’s how to overcome the frustration.

This is a good script if you know or control your system so that you know that the local TZ in your OS is correct. Unfortunately, this script still creates an warning message under BSD UNIX.

To fix this, just add an «@» in front of «localtime» as:

Источник

Класс DateTime

(PHP 5 >= 5.2.0, PHP 7, PHP 8)

Введение

Обзор классов

Список изменений

Содержание

User Contributed Notes 26 notes

Set Timezone and formatting.

= time ();
$timeZone = new \ DateTimeZone ( ‘Asia/Tokyo’ );

DateTime supports microseconds since 5.2.2. This is mentioned in the documentation for the date function, but bears repeating here. You can create a DateTime with fractional seconds and retrieve that value using the ‘u’ format string.

// Instantiate a DateTime with microseconds.
$d = new DateTime ( ‘2011-01-01T15:03:01.012345Z’ );

There is a subtle difference between the following two statments which causes JavaScript’s Date object on iPhones to fail.

/**
On my local machine this results in:

Both of these strings are valid ISO8601 datetime strings, but the latter is not accepted by the constructor of JavaScript’s date object on iPhone. (Possibly other browsers as well)
*/

?>

Our solution was to create the following constant on our DateHelper object.

class DateHelper
<
/**
* An ISO8601 format string for PHP’s date functions that’s compatible with JavaScript’s Date’s constructor method
* Example: 2013-04-12T16:40:00-04:00
*
* PHP’s ISO8601 constant doesn’t add the colon to the timezone offset which is required for iPhone
**/
const ISO8601 = ‘Y-m-d\TH:i:sP’ ;
>
?>

Small but powerful extension to DateTime

class Blar_DateTime extends DateTime <

= new Blar_DateTime ( ‘1879-03-14’ );

Albert Einstein would now be 130 years old.

Albert Einstein would now be 130 Years, 10 Months, 10 Days old.

Albert Einstein was on 2010-10-10 131 years old.

Example displaying each time format:

$dateTime = new DateTime();

The above example will output:

At PHP 7.1 the DateTime constructor incorporates microseconds when constructed from the current time. Make your comparisons carefully, since two DateTime objects constructed one after another are now more likely to have different values.

This caused some confusion with a blog I was working on and just wanted to make other people aware of this. If you use createFromFormat to turn a date into a timestamp it will include the current time. For example:

if you’d like to print all the built-in formats,

This might be unexpected behavior:

#or use the interval
#$date1->add(new DateInterval(«P1M»));

#will produce 2017-10-1
#not 2017-09-30

A good way I did to work with millisecond is transforming the time in milliseconds.

function timeToMilliseconds($time) <
$dateTime = new DateTime($time);

If you have timezone information in the time string you construct the DateTime object with, you cannot add an extra timezone in the constructor. It will ignore the timezone information in the time string:

$date = new DateTime(«2010-07-05T06:00:00Z», new DateTimeZone(«Europe/Amsterdam»));

will create a DateTime object set to «2010-07-05 06:00:00+0200» (+2 being the TZ offset for Europe/Amsterdam)

To get this done, you will need to set the timezone separately:

$date = new DateTime(«2010-07-05T06:00:00Z»);
$date->setTimeZone(new DateTimeZone(«Europe/Amsterdam»);

This will create a DateTime object set to «2010-07-05 08:00:00+0200»

It isn’t obvious from the above, but you can insert a letter of the alphabet directly into the date string by escaping it with a backslash in the format string. Note that if you are using «double» speech marks around the format string, you will have to further escape each backslash with another backslash! If you are using ‘single’ speech marks around the format string, then you only need one backslash.

For instance, to create a string like «Y2014M01D29T1633», you *could* use string concatenation like so:

please note that using

setTimezone
setTimestamp
setDate
setTime
etc..

$original = new DateTime(«now»);

so a datetime object is mutable

(Editors note: PHP 5.5 adds DateTimeImmutable which does not modify the original object, instead creating a new instance.)

Create function to convert GregorianDate to JulianDayCount

Note that the ISO8601 constant will not correctly parse all possible ISO8601 compliant formats, as it does not support fractional seconds. If you need to be strictly compliant to that standard you will have to write your own format.

Bug report #51950 has unfortunately be closed as «not a bug» even though it’s a clear violation of the ISO8601 standard.

It seems like, due to changes in the DateTimeZone class in PHP 5.5, when creating a date and specifying the timezone as a a string like ‘EDT’, then getting the timezone from the date object and trying to use that to set the timezone on a date object you will have problems but never know it. Take the following code:

Be aware that DateTime may ignore fractional seconds for some formats, but not when using the ISO 8601 time format, as documented by this bug:

$dateTime = DateTime::createFromFormat(
DateTime::ISO8601,
‘2009-04-16T12:07:23.596Z’
);
// bool(false)

Be aware of this behaviour:

In my opinion, the former date should be adjusted to 2014/11/30, that is, the last day in the previous month.

Here is easiest way to find the days difference between two dates:

If you’re stuck on a PHP 5.1 system (unfortunately one of my clients is on a rather horrible webhost who claims they cannot upgrade php) you can use this as a quick workaround:

If you need DateTime::createFromFormat functionality in versions class DateClass extends DateTime <

$regexpArray [ ‘Y’ ] = «(?P 19|20\d\d)» ;
$regexpArray [ ‘m’ ] = «(?P 04|1[012])» ;
$regexpArray [ ‘d’ ] = «(?P 03|[12]1|3[01])» ;
$regexpArray [ ‘-‘ ] = «[-]» ;
$regexpArray [ ‘.’ ] = «[\. /.]» ;
$regexpArray [ ‘:’ ] = «[:]» ;
$regexpArray [ ‘space’ ] = «[\s]» ;
$regexpArray [ ‘H’ ] = «(?P 04|15|23)» ;
$regexpArray [ ‘i’ ] = «(?P41)» ;
$regexpArray [ ‘s’ ] = «(?P18)» ;

Источник

Different timezone_types on DateTime object

created_at datetimetz:

birthdate date:

How can I achieve that?

php datetime set timezone. Смотреть фото php datetime set timezone. Смотреть картинку php datetime set timezone. Картинка про php datetime set timezone. Фото php datetime set timezone

2 Answers 2

Timezones can be one of three different types in DateTime objects:

Only DateTime objects with type 3 timezones attached will allow for DST correctly.

In order to always have type 3 you will need to store the timezone in your database as accepted identifiers from this list and apply it to your DateTime object on instantiation.

I know this is an ancient post, but since Doctrine was mentioned, I feel the need to share what I’ve recently experienced regarding this issue.

@vascowhite is correct, but regarding Doctrine (at least on my configuration) dates sent to the server (e.g. to save) via HTTP are converted timezone type 2. Doctrine handles them properly and saves the date correctly, but it does not convert the timezone type.

If you are performing a «save and and return fresh values» type operation, note that Doctrine will use the cached value (with timezone_type 2). This becomes important when you are expecting timezone_type 3 as you would normally get during a page reload. We have a custom date converter JS class that expects timezone_type 3 and it was unable to convert it. Admittedly, the date converter should account for this, but also one should be aware that the timezone type will be the last loaded value in Doctrine. Clearing Doctrine’s cache after saving will force the data to reload with timezone_type 3.

Источник

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *