Blog de programación, errores, soluciones

Chose Language:
comments
Author: Admin/Publisher |finished | checked

PHP DateTimeZone Class

The PHP DateTimeZone class is responsible for representing a timezone.

Below we can see the class description, which shows its constants as well as its methods.

Description / Descripción
 class DateTimeZone {
/* Constants */
const int AFRICA = 1;
const int AMERICA = 2;
const int ANTARCTICA = 4;
const int ARCTIC = 8;
const int ASIA = 16;
const int ATLANTIC = 32;
const int AUSTRALIA = 64;
const int EUROPE = 128;
const int INDIAN = 256;
const int PACIFIC = 512;
const int UTC = 1024;
const int ALL = 2047;
const int ALL_WITH_BC = 4095;
const int PER_COUNTRY = 4096;
/* Methods */
public __construct(string $timezone)
public getLocation(): array|false
public getName(): string
public getOffset(DateTimeInterface $datetime): int
public getTransitions(int $timestampBegin = PHP_INT_MIN, int $timestampEnd = PHP_INT_MAX): array|false
public static listAbbreviations(): array
public static listIdentifiers(int $timezoneGroup = DateTimeZone::ALL, ?string $countryCode = null): array
}
In this post, we will use $obj as a reference to the object created with the class.

Constants

Let’s make a small example with a constant:

getting the zone constat
<?php
$zone = DateTimeZone::AFRICA;
echo $zone;

OK, but this doesn’t seem too useful, where do we use the constants?

Let’s do a second example, this time creating a new DateTimeZone.

getting all Africa Timezone
<?php
$d = new DateTimeZone("Africa/Abidjan");
$thelist=$d->listIdentifiers(DateTimeZone::AFRICA);
echo var_dump($thelist);
array(52) {
  [0]=>
  string(14) "Africa/Abidjan"
  [1]=>
  string(12) "Africa/Accra"
  [2]=>
  string(18) "Africa/Addis_Ababa"
  [3]=>
  string(14) "Africa/Algiers"
  [4]=>
  string(13) "Africa/Asmara"
  [5]=>
  string(13) "Africa/Bamako"
  [6]=>
  string(13) "Africa/Bangui"
  [7]=>
  string(13) "Africa/Banjul"
  [8]=>
  string(13) "Africa/Bissau"
  [9]=>
  string(15) "Africa/Blantyre"
  [10]=>
  string(18) "Africa/Brazzaville"
  [11]=>
  string(16) "Africa/Bujumbura"
  [12]=>
  string(12) "Africa/Cairo"
  [13]=>
  string(17) "Africa/Casablanca"
  [14]=>
  string(12) "Africa/Ceuta"
  [15]=>
  string(14) "Africa/Conakry"
  [16]=>
  string(12) "Africa/Dakar"
  [17]=>
  string(20) "Africa/Dar_es_Salaam"
  [18]=>
  string(15) "Africa/Djibouti"
  [19]=>
  string(13) "Africa/Douala"
  [20]=>
  string(15) "Africa/El_Aaiun"
  [21]=>
  string(15) "Africa/Freetown"
  [22]=>
  string(15) "Africa/Gaborone"
  [23]=>
  string(13) "Africa/Harare"
  [24]=>
  string(19) "Africa/Johannesburg"
  [25]=>
  string(11) "Africa/Juba"
  [26]=>
  string(14) "Africa/Kampala"
  [27]=>
  string(15) "Africa/Khartoum"
  [28]=>
  string(13) "Africa/Kigali"
  [29]=>
  string(15) "Africa/Kinshasa"
  [30]=>
  string(12) "Africa/Lagos"
  [31]=>
  string(17) "Africa/Libreville"
  [32]=>
  string(11) "Africa/Lome"
  [33]=>
  string(13) "Africa/Luanda"
  [34]=>
  string(17) "Africa/Lubumbashi"
  [35]=>
  string(13) "Africa/Lusaka"
  [36]=>
  string(13) "Africa/Malabo"
  [37]=>
  string(13) "Africa/Maputo"
  [38]=>
  string(13) "Africa/Maseru"
  [39]=>
  string(14) "Africa/Mbabane"
  [40]=>
  string(16) "Africa/Mogadishu"
  [41]=>
  string(15) "Africa/Monrovia"
  [42]=>
  string(14) "Africa/Nairobi"
  [43]=>
  string(15) "Africa/Ndjamena"
  [44]=>
  string(13) "Africa/Niamey"
  [45]=>
  string(17) "Africa/Nouakchott"
  [46]=>
  string(18) "Africa/Ouagadougou"
  [47]=>
  string(17) "Africa/Porto-Novo"
  [48]=>
  string(15) "Africa/Sao_Tome"
  [49]=>
  string(14) "Africa/Tripoli"
  [50]=>
  string(12) "Africa/Tunis"
  [51]=>
  string(15) "Africa/Windhoek"
}

Lista de Constantes

  • DateTimeZone::AFRICA
    • Africa time zones.
  • DateTimeZone::AMERICA
    • America time zones.
  • DateTimeZone::ANTARCTICA
    • Antarctica time zones.
  • DateTimeZone::ARCTIC
    • Arctic time zones.
  • DateTimeZone::ASIA
    • Asia time zones.
  • DateTimeZone::ATLANTIC
    • Atlantic time zones.
  • DateTimeZone::AUSTRALIA
    • Australia time zones.
  • DateTimeZone::EUROPE
    • Europe time zones.
  • DateTimeZone::INDIAN
    • Indian time zones.
  • DateTimeZone::PACIFIC
    • Pacific time zones.
  • DateTimeZone::UTC
    • UTC time zones.
  • DateTimeZone::ALL
    • All time zones.
  • DateTimeZone::ALL_WITH_BC
    • All time zones including backwards compatible.
  • DateTimeZone::PER_COUNTRY
    • Time zones per country.

I think that’s enough to understand the constants, let’s now take a look at the methods

Métodos

In this section, we will see the different methods that DateTimeZone has.

__construct

The constructor method has one mandatory argument, which creates a new DateTimeZone object. $timezone must be a string and can take the following values: timezone name, offset value like "+0200", "-0100", or timezone abbreviation like "BST", "CEST", etc.

Description
public DateTimeZone::__construct(string $timezone)

I won’t provide examples, since they were already mentioned in the constants section.

getLocation()

Returns information about a timezone

Description
public DateTimeZone::getLocation(): array
Sintaxis
$obj->getLocation()

Returns an array containing information about the timezone, or false on failure.

getLocation Example
<?php
$tz = new DateTimeZone("America/Costa_Rica");
print_r($tz->getLocation());
?>
Array
(
    [country_code] => CR
    [latitude] => 9.93333
    [longitude] => -84.08334
    [comments] => 
)

Although this method may not seem useful, knowing the country code can be really helpful.

getName

Returns the timezone name as a string

Description
public DateTimeZone::getName(): string
Sintaxis
$obj->getName()
getName method exampe
<?php
$tz = new DateTimeZone("America/Costa_Rica");
print_r($tz->getName());
?>
America/Costa_Rica

getOffset

Returns the timezone’s GMT offset in seconds from UTC (Coordinated Universal Time), also known as Greenwich Mean Time (GMT) offset.

Description
public DateTimeZone::getOffset(DateTime $datetime): int
Sintaxis
$obj->getOffset($datetime)

In the PHP website there’s an example about this, but I’ve modified it a bit to use Uruguay and Spain as reference countries. Spain is 2 hours ahead of GMT, and Uruguay is 3 hours behind at the time of writing this post

<?php

$dateTimeZoneMontevideo = new DateTimeZone("America/Montevideo");
$dateTimeZoneMadrid = new DateTimeZone("Europe/Madrid");

$dateTimeMontevideo = new DateTime("now", $dateTimeZoneMontevideo);
$dateTimeMadrid = new DateTime("now", $dateTimeZoneMadrid);

$timeOffset = $dateTimeZoneMadrid->getOffset($dateTimeMontevideo);
$timeOffset2= $dateTimeZoneMontevideo->getOffset($dateTimeMadrid);


var_dump($timeOffset);
var_dump($timeOffset2);
int(7200)
int(-10800)

We can see that this integer represents the hours of Spain and Uruguay in seconds, since 7200 ÷ 60 ÷ 60 = 2 and -10800 ÷ 60 ÷ 60 = -3

getTransitions

This method returns the transitions of the timezone. Keep in mind that many countries have multiple timezones cause of the DST(Daylight Saving Time). For example, Uruguay is 3 hours behind GMT, but during summer this time changes.

method description
public DateTimeZone::getTransitions(int $timestampBegin = PHP_INT_MIN, int $timestampEnd = PHP_INT_MAX): array|false
Sintaxis
$obj->getTransitions($timestampBegin,$timestampEnd)

The method description shows that we have a start timestamp and an end timestamp. With them, we define the period in which we want to obtain the transitions.

getTransition Example
<?php
$zona_horaria = new DateTimeZone("America/Montevideo");
$transiciones = $zona_horaria->getTransitions(631152000,PHP_INT_MAX);//631152000 se refiere al año 1990
print_r(array_slice($transiciones, 0, 3));
?>

This would be the first 3 transitions since 1990.

DateTimeZone::listAbbreviations

Returns an associative array containing the DST(Daylight Saving Time), offset, and the timezone name

Description
public static DateTimeZone::listAbbreviations(): array
Sintaxis
DateTimeZone::listAbbreviations()

For Example:

getting all abbreviations from Australia
<?php
$timezone_abbreviations = DateTimeZone::listAbbreviations();
print_r($timezone_abbreviations["acst"]);
?>

In this example, all the abbreviations for ACST (Australian Central Standard Time) will be obtained.

DateTimeZone::listIdentifiers

This returns a numerically indexed array containing all the defined time zone identifiers.

Description
public static DateTimeZone::listIdentifiers(int $timezoneGroup = DateTimeZone::ALL, ?string $countryCode = null)
Sintaxis
DateTimeZone::listIdentifiers($timezoneGroup,$countryCode)

We have already done an example of listidentifiers before in constants, but I made a mistake that you should not make and that is that I called the method with -> instead of :: although it worked anyway, this does not always work.

in PHP you use the scope resolution operator :: to call static methods or access static properties

Let’s see a simple example with the identifiers of Australia.

listIdentifiers example
<?php
$timezone_identifiers = DateTimeZone::listIdentifiers(DateTimeZone::AUSTRALIA);
var_dump($timezone_identifiers)
?>
array(11) {
  [0]=>
  string(18) "Australia/Adelaide"
  [1]=>
  string(18) "Australia/Brisbane"
  [2]=>
  string(21) "Australia/Broken_Hill"
  [3]=>
  string(16) "Australia/Darwin"
  [4]=>
  string(15) "Australia/Eucla"
  [5]=>
  string(16) "Australia/Hobart"
  [6]=>
  string(18) "Australia/Lindeman"
  [7]=>
  string(19) "Australia/Lord_Howe"
  [8]=>
  string(19) "Australia/Melbourne"
  [9]=>
  string(15) "Australia/Perth"
  [10]=>
  string(16) "Australia/Sydney"
}
Category: en-php
Something wrong? If you found an error or mistake in the content you can contact me on Twitter | @luisg2249_luis.
Last 4 post in same category

Comments