Sell And Buy

Tuesday 17 March 2015

PHP date functions and its Use

Introduction

When you post an article on a blog, you have to display the date that it was published. When you updated a record in a database, you need to record the last update date for auditing purposes. Copyright notices on website need to display the current year too. PHP date functions are the ones that make the above possible. PHP has built in functions that simplify working with date data types.

What is the Date Function?

The PHP date function is used to format a date or time into a human readable format. It has the following basic syntax
?
1
2
3
<?php
date(format,[timestamp]);
?>
HERE,
  • “date(…)” is the function that returns the current time on the server.
  • “format” is the general format which we want our output to be i.e.;
    • “Y-m-d” for MySQL date format YYYY-MM-DD
    • “Y” to display the current year
    • “[timestamp]” is optional. If no timestamp has been provided, PHP will get the use the current date and time on the server.
Let’s look at a basic example that displays the current year.
1
<?php
2
3
echo date("Y");
4
5
?>

2015

Testing our code

Let’s assume you have saved the file simple_date.php in phptuts, browse to the URL http://localhost/phptuts/simple_date.php
simple_date

What is a timestamp?

 A timestamp is a numeric value in seconds between the current time and value as at 1st January, 1970 00:00:00 Greenwich Mean Time (GMT).  The value returned by the time function depends on the default time zone. The default time zone is set in the php.ini file. It can also be set programmatically using date_default_timezone_set function. The code below displays the current time stamp
1
<?php
2
3
echo time();
4
5
?>
This code is editable. Click Run to Compile + Execute

1426576599
Assuming you saved the file timestamp.php in phptuts folder, browse to the URL http://localhost/phptuts/timestamp.php
timestamp
Note: the value of the timestamp is not a constant. It changes every second.

Getting a list of available time zone identifiers

Before we look at how to set the default time zone programmatically, let’s look at how to get a list of supported time zones.
1
<?php
2
3
$timezone_identifiers = DateTimeZone::listIdentifiers();
4
5
foreach($timezone_identifiers as $key => $list){
6
7
echo $list . "<br/>";
8
9
}
10
11
?>
This code is editable. Click Run to Compile + Execute

Africa/Abidjan
Africa/Accra
Africa/Addis_Ababa
Africa/Algiers
Africa/Asmara
Africa/Bamako
Africa/Bangui
Africa/Banjul
Africa/Bissau
Africa/Blantyre
Africa/Brazzaville
Africa/Bujumbura
Africa/Cairo
Africa/Casablanca
Africa/Ceuta
Africa/Conakry
Africa/Dakar
Africa/Dar_es_Salaam
Africa/Djibouti
Africa/Douala
Africa/El_Aaiun
Africa/Freetown
Africa/Gaborone
Africa/Harare
Africa/Johannesburg
Africa/Juba
Africa/Kampala
Africa/Khartoum
Africa/Kigali
Africa/Kinshasa
Africa/Lagos
Africa/Libreville
Africa/Lome
Africa/Luanda
Africa/Lubumbashi
Africa/Lusaka
Africa/Malabo
Africa/Maputo
Africa/Maseru
Africa/Mbabane
Africa/Mogadishu
Africa/Monrovia
Africa/Nairobi
Africa/Ndjamena
Africa/Niamey
Africa/Nouakchott
Africa/Ouagadougou
Africa/Porto-Novo
Africa/Sao_Tome
Africa/Tripoli
Africa/Tunis
Africa/Windhoek
America/Adak
America/Anchorage
America/Anguilla
America/Antigua
America/Araguaina
America/Argentina/Buenos_Aires
America/Argentina/Catamarca
America/Argentina/Cordoba
America/Argentina/Jujuy
America/Argentina/La_Rioja
America/Argentina/Mendoza
America/Argentina/Rio_Gallegos
America/Argentina/Salta
America/Argentina/San_Juan
America/Argentina/San_Luis
America/Argentina/Tucuman
America/Argentina/Ushuaia
America/Aruba
America/Asuncion
America/Atikokan
America/Bahia
America/Bahia_Banderas
America/Barbados
America/Belem
America/Belize
America/Blanc-Sablon
America/Boa_Vista
America/Bogota
America/Boise
America/Cambridge_Bay
America/Campo_Grande
America/Cancun
America/Caracas
America/Cayenne
America/Cayman
America/Chicago
America/Chihuahua
America/Costa_Rica
America/Creston
America/Cuiaba
America/Curacao
America/Danmarkshavn
America/Dawson
America/Dawson_Creek
America/Denver
America/Detroit
America/Dominica
America/Edmonton
America/Eirunepe
America/El_Salvador
America/Fortaleza
America/Glace_Bay
America/Godthab
America/Goose_Bay
America/Grand_Turk
America/Grenada
America/Guadeloupe
America/Guatemala
America/Guayaquil
America/Guyana
America/Halifax
America/Havana
America/Hermosillo
America/Indiana/Indianapolis
America/Indiana/Knox
America/Indiana/Marengo
America/Indiana/Petersburg
America/Indiana/Tell_City
America/Indiana/Vevay
America/Indiana/Vincennes
America/Indiana/Winamac
America/Inuvik
America/Iqaluit
America/Jamaica
America/Juneau
America/Kentucky/Louisville
America/Kentucky/Monticello
America/Kralendijk
America/La_Paz
America/Lima
America/Los_Angeles
America/Lower_Princes
America/Maceio
America/Managua
America/Manaus
America/Marigot
America/Martinique
America/Matamoros
America/Mazatlan
America/Menominee
America/Merida
America/Metlakatla
America/Mexico_City
America/Miquelon
America/Moncton
America/Monterrey
America/Montevideo
America/Montserrat
America/Nassau
America/New_York
America/Nipigon
America/Nome
America/Noronha
America/North_Dakota/Beulah
America/North_Dakota/Center
America/North_Dakota/New_Salem
America/Ojinaga
America/Panama
America/Pangnirtung
America/Paramaribo
America/Phoenix
America/Port-au-Prince
America/Port_of_Spain
America/Porto_Velho
America/Puerto_Rico
America/Rainy_River
America/Rankin_Inlet
America/Recife
America/Regina
America/Resolute
America/Rio_Branco
America/Santa_Isabel
America/Santarem
America/Santiago
America/Santo_Domingo
America/Sao_Paulo
America/Scoresbysund
America/Sitka
America/St_Barthelemy
America/St_Johns
America/St_Kitts
America/St_Lucia
America/St_Thomas
America/St_Vincent
America/Swift_Current
America/Tegucigalpa
America/Thule
America/Thunder_Bay
America/Tijuana
America/Toronto
America/Tortola
America/Vancouver
America/Whitehorse
America/Winnipeg
America/Yakutat
America/Yellowknife
Antarctica/Casey
Antarctica/Davis
Antarctica/DumontDUrville
Antarctica/Macquarie
Antarctica/Mawson
Antarctica/McMurdo
Antarctica/Palmer
Antarctica/Rothera
Antarctica/Syowa
Antarctica/Troll
Antarctica/Vostok
Arctic/Longyearbyen
Asia/Aden
Asia/Almaty
Asia/Amman
Asia/Anadyr
Asia/Aqtau
Asia/Aqtobe
Asia/Ashgabat
Asia/Baghdad
Asia/Bahrain
Asia/Baku
Asia/Bangkok
Asia/Beirut
Asia/Bishkek
Asia/Brunei
Asia/Chita
Asia/Choibalsan
Asia/Colombo
Asia/Damascus
Asia/Dhaka
Asia/Dili
Asia/Dubai
Asia/Dushanbe
Asia/Gaza
Asia/Hebron
Asia/Ho_Chi_Minh
Asia/Hong_Kong
Asia/Hovd
Asia/Irkutsk
Asia/Jakarta
Asia/Jayapura
Asia/Jerusalem
Asia/Kabul
Asia/Kamchatka
Asia/Karachi
Asia/Kathmandu
Asia/Khandyga
Asia/Kolkata
Asia/Krasnoyarsk
Asia/Kuala_Lumpur
Asia/Kuching
Asia/Kuwait
Asia/Macau
Asia/Magadan
Asia/Makassar
Asia/Manila
Asia/Muscat
Asia/Nicosia
Asia/Novokuznetsk
Asia/Novosibirsk
Asia/Omsk
Asia/Oral
Asia/Phnom_Penh
Asia/Pontianak
Asia/Pyongyang
Asia/Qatar
Asia/Qyzylorda
Asia/Rangoon
Asia/Riyadh
Asia/Sakhalin
Asia/Samarkand
Asia/Seoul
Asia/Shanghai
Asia/Singapore
Asia/Srednekolymsk
Asia/Taipei
Asia/Tashkent
Asia/Tbilisi
Asia/Tehran
Asia/Thimphu
Asia/Tokyo
Asia/Ulaanbaatar
Asia/Urumqi
Asia/Ust-Nera
Asia/Vientiane
Asia/Vladivostok
Asia/Yakutsk
Asia/Yekaterinburg
Asia/Yerevan
Atlantic/Azores
Atlantic/Bermuda
Atlantic/Canary
Atlantic/Cape_Verde
Atlantic/Faroe
Atlantic/Madeira
Atlantic/Reykjavik
Atlantic/South_Georgia
Atlantic/St_Helena
Atlantic/Stanley
Australia/Adelaide
Australia/Brisbane
Australia/Broken_Hill
Australia/Currie
Australia/Darwin
Australia/Eucla
Australia/Hobart
Australia/Lindeman
Australia/Lord_Howe
Australia/Melbourne
Australia/Perth
Australia/Sydney
Europe/Amsterdam
Europe/Andorra
Europe/Athens
Europe/Belgrade
Europe/Berlin
Europe/Bratislava
Europe/Brussels
Europe/Bucharest
Europe/Budapest
Europe/Busingen
Europe/Chisinau
Europe/Copenhagen
Europe/Dublin
Europe/Gibraltar
Europe/Guernsey
Europe/Helsinki
Europe/Isle_of_Man
Europe/Istanbul
Europe/Jersey
Europe/Kaliningrad
Europe/Kiev
Europe/Lisbon
Europe/Ljubljana
Europe/London
Europe/Luxembourg
Europe/Madrid
Europe/Malta
Europe/Mariehamn
Europe/Minsk
Europe/Monaco
Europe/Moscow
Europe/Oslo
Europe/Paris
Europe/Podgorica
Europe/Prague
Europe/Riga
Europe/Rome
Europe/Samara
Europe/San_Marino
Europe/Sarajevo
Europe/Simferopol
Europe/Skopje
Europe/Sofia
Europe/Stockholm
Europe/Tallinn
Europe/Tirane
Europe/Uzhgorod
Europe/Vaduz
Europe/Vatican
Europe/Vienna
Europe/Vilnius
Europe/Volgograd
Europe/Warsaw
Europe/Zagreb
Europe/Zaporozhye
Europe/Zurich
Indian/Antananarivo
Indian/Chagos
Indian/Christmas
Indian/Cocos
Indian/Comoro
Indian/Kerguelen
Indian/Mahe
Indian/Maldives
Indian/Mauritius
Indian/Mayotte
Indian/Reunion
Pacific/Apia
Pacific/Auckland
Pacific/Bougainville
Pacific/Chatham
Pacific/Chuuk
Pacific/Easter
Pacific/Efate
Pacific/Enderbury
Pacific/Fakaofo
Pacific/Fiji
Pacific/Funafuti
Pacific/Galapagos
Pacific/Gambier
Pacific/Guadalcanal
Pacific/Guam
Pacific/Honolulu
Pacific/Johnston
Pacific/Kiritimati
Pacific/Kosrae
Pacific/Kwajalein
Pacific/Majuro
Pacific/Marquesas
Pacific/Midway
Pacific/Nauru
Pacific/Niue
Pacific/Norfolk
Pacific/Noumea
Pacific/Pago_Pago
Pacific/Palau
Pacific/Pitcairn
Pacific/Pohnpei
Pacific/Port_Moresby
Pacific/Rarotonga
Pacific/Saipan
Pacific/Tahiti
Pacific/Tarawa
Pacific/Tongatapu
Pacific/Wake
Pacific/Wallis
UTC
  HERE,
  • “$timezone_identifiers = DateTimeZone::listIdentifiers();” calls the listIdentifiers static method of the DateTimeZone built in class. The listIdentifiers method returns a list of constants that are assigned to the variable $timezone_identifiers.
  • “foreach{…}” iterates through the numeric array and prints the values.
Assuming you saved the file list_time_zones.php in phptuts folder, browse to the URL http://localhost/phptuts/list_time_zones.php
list_time_zones

Setting the default time zone programmatically

The date_default_timezone_set function allows you to set the default time zone from a PHP script. The set time zone will then be used by all date function scripts. It has the following syntax.
?
1
2
3
<?php
date_default_timezone_set ( string $timezone_identifier );
?>
HERE,
  • “date_default_timezone_set()” is the function that sets the default time zone
  • “string $timezone_identifier” is the time zone identifier
The script below displays the time according to the default time zone set in php.ini. It then changes the default time zone to Asia/Calcutta and displays the time again.
1
<?php
2
echo "The time in " . date_default_timezone_get() . " is " . date("H:i:s");
3
4
date_default_timezone_set("Asia/Calcutta");
5
echo "The time in " . date_default_timezone_get() . " is " . date("H:i:s");
6
?>
This code is editable. Click Run to Compile + Execute

The time in America/Los_Angeles is 00:16:09The time in Asia/Calcutta is 12:46:09
  Assuming you have saved the file set_time_zone.php in the phptuts folder, browse to the URL http://localhost/phptuts/set_time_zone.php
timezone

Mktime function

The mktime function returns the timestamp in a UNIX format. It has the following syntax.
?
1
2
3
<?php
mktime(hour, minute, second, month, day, year, is_dst);
?>
HERE,
  • “mktime(…)” is the make timestamp function
  • “hour” is optional, it is the number of hour
  • “minute” is optional, it is the number of minutes
  • “second” is optional, it is the number of seconds
  • “month” is optional, it is the number of the month
  • “day” is optional, it is the number of the day
  • “year” is optional, it is the number of the year
  • “is_dst” is optional, it is used to determine the day saving time (DST). 1 is for DST, 0 if it is not and -1 if it is unknown.
Let’s now look at an example that creates a timestamp for the date 13/10/2012 using the mktime function.
1
<?php
2
3
echo mktime(0,0,0,10,13,2012);
4
5
?>
This code is editable. Click Run to Compile + Execute

1350111600
  HERE,
  • “0,0,0” is the hour, minute and seconds respectively.
  • “13” is the day of the month
  • “10” is the month of the year
  • “2012” is the year
Assuming you saved the file mktime.php in the folder phptus, browse to the URL http://localhost/phptuts/mktime.php
mktime

PHP Date function reference

The table below shows the common parameters used when working with the date function.

Time parameters

Parameter Description Example
“r” Returns the full date and time
1
<?php
2
echo date("r");
3
?>
This code is editable. Click Run to Compile + Execute

Tue, 17 Mar 2015 00:16:01 -0700
“a”,”A” Returns whether the current time is am or pm, AM or PM respectively
1
<?php
2
echo date("a");
3
echo date("A");
4
?>
This code is editable. Click Run to Compile + Execute

amAM
“g”,”G” Returns the hour without leading zeroes [1 to 12], [0 to 23] respectively
1
<?php
2
echo date("g"); 
3
echo date("G");
4
?>
This code is editable. Click Run to Compile + Execute

120
“h”,”H” Returns the hour with leading zeros [01 to 12],[00 to 23] respectively
1
<?php
2
echo date("h"); 
3
echo date("H");
4
?>
This code is editable. Click Run to Compile + Execute

1200
“i”,”s” Returns the minutes/seconds with leading zeroes [00 to 59]
1
<?php
2
echo date("i"); 
3
echo date("s");
4
?>
This code is editable. Click Run to Compile + Execute

1552

Day parameters

Parameter Description Example
“d” Returns the day of the month with leading zeroes [01 to 31]
1
<?php
2
echo date("d");
3
?>
This code is editable. Click Run to Compile + Execute

17
“j” Returns the day of the month without leading zeroes [1 to 31]
1
<?php
2
echo date("j");
3
?>
This code is editable. Click Run to Compile + Execute

17
“D” Returns the first 3 letters of the day name [Sub to Sat]
1
<?php
2
echo date("D");
3
?>
This code is editable. Click Run to Compile + Execute

Tue
“l” Returns day name of the week [Sunday to Saturday]
1
<?php
2
echo date("l");
3
?>
This code is editable. Click Run to Compile + Execute

Tuesday
“w” Returns day of the week without leading zeroes [0 to 6] Sunday is represent by zero (0) through to Saturday represented by six (6)
1
<?php
2
echo date("w");
3
?>
This code is editable. Click Run to Compile + Execute

2
“z” Returns the day of the year without leading spaces [0 through to 365]
1
<?php
2
echo date("z");
3
?>
This code is editable. Click Run to Compile + Execute

75

Month Parameters

Parameter Description Example
“m” Returns the month number with leading zeroes [01 to 12]
1
<?php
2
echo date("m");
3
?>
This code is editable. Click Run to Compile + Execute

03
“n” Returns the month number without leading zeroes [01 to 12]
1
<?php
2
echo date("n");
3
?>
This code is editable. Click Run to Compile + Execute

3
“M” Returns the first 3 letters of the month name [Jan to Dec]
1
<?php
2
echo date("M");
3
?>
This code is editable. Click Run to Compile + Execute

Mar
“F” Returns the month name [January to December]
1
<?php
2
echo date("F");
3
?>
This code is editable. Click Run to Compile + Execute

March
“t” Returns the number of days in a month [28 to 31]
1
<?php
2
echo date("t");
3
?>
This code is editable. Click Run to Compile + Execute

31

Year Parameters

Parameter Description Example
“L” Returns 1 if it’s a leap year and 0 if it is not a leap year
1
<?php
2
echo date("L");
3
?>
This code is editable. Click Run to Compile + Execute

0
“Y” Returns four digit year format
1
<?php
2
echo date("Y");
3
?>
This code is editable. Click Run to Compile + Execute

2015
“y” Returns two (2) digits year format (00 to 99)
1
<?php
2
echo date("y");
3
?>
This code is editable. Click Run to Compile + Execute

15

Summary

  • The date function is used to format the timestamp into a human desired format.
  • The timestamp is the number of seconds between the current time and 1st January, 1970 00:00:00 GMT. It is also known as the UNIX timestamp.
  • All date functions use the default time zone set in the php.ini file
  • The default time zone can also be set programmatically using PHP scripts.

No comments:

Post a Comment