Introduction to Date and Time in PHP

This tutorial will concentrate on the time and date functions provided in PHP.

This tutorial assumes several things about the reader:

  • You are familiar with PHP.
  • You have access to a server or servers running the PHP package.

The most commonly used function used when dealing with dates and time is the date () function. It is a PHP function which returns the current date and time, and allows you to format the output as you like. As we proceed, you will see that this function is very simple to use, and has many parameters available to it.

We will also introduce the time () function in detail, learning how to handle and manipulate the UNIX timestamp it returns.

Current Date and Time

The date () function provides you with a means of retrieving the current date and time, applying the format integer parameters indicated in your script to the timestamp provided or the current local time if no timestamp is given. In simplified terms, passing a time parameter is optional-if you don’t, the current timestamp will be used.

string date ( string format [, int timestamp])
This function provides many possible formatting options. You can also customize the output from the format string. Following is a full list of the formatting options available:

a => “am” or “pm”
A => “AM” or “PM”
B => Swatch Internet time
d => day of the month, 2 digits with leading zeros; i.e. “01” to “31”
D => day of the week, textual, 3 letters; i.e. “Fri”
F => month, textual, long; i.e. “January”
g => hour, 12-hour format without leading zeros; i.e. “1” to “12”
G => hour, 24-hour format without leading zeros; i.e. “0” to “23”
h => hour, 12-hour format; i.e. “01” to “12”
H => hour, 24-hour format; i.e. “00” to “23”
i => minutes; i.e. “00” to “59”
I => (capital i) “1” if Daylight Savings Time, “0” otherwise.
j => day of the month without leading zeros; i.e. “1” to “31”
l => (lowercase ‘L’) day of the week, textual, long; i.e. “Friday”
L => boolean for whether it is a leap year; i.e. “0” or “1”
m => month; i.e. “01” to “12”
M => month, textual, 3 letters; i.e. “Jan”
n => month without leading zeros; i.e. “1” to “12”
r => RFC 822 formatted date; i.e. “Thu, 21 Dec 2000 16:01:07 +0200” (added in PHP 4.0.4)
s => seconds; i.e. “00” to “59”
S => English ordinal suffix, textual, 2 characters; i.e. “th”, “nd”
t => number of days in the given month; i.e. “28” to “31”
T => Timezone setting of this machine; i.e. “MDT”
U => seconds since the epoch
w => day of the week, numeric, i.e. “0” (Sunday) to “6” (Saturday)
Y => year, 4 digits; i.e. “1999”
y => year, 2 digits; i.e. “99”
z => day of the year; i.e. “0” to “365”
Z => timezone offset in seconds (i.e. “-43200” to “43200”). The offset for timezones west of UTC is always negative, and for those east of UTC is always positive.

Following are some examples you can try, note the formatting characters added:

<?php
echo date("d-M-Y")."<br>";
echo date("d^^^M^^^Y")."<br>";
echo date("D dS M,Y h:i a")."<br>";
?>

The list above outlines all possible variations of the date/time. Play around with the various combinations., you will find that almost any possibility is available for use.

The date function can also accept a timestamp (often called a Unix timestamp), which is the number of seconds since January 1, 1970 (starting at 1 second after midnight). By default, the date function takes the current timestamp, but you can pass the function any timestamp you want:

<?php
echo date("l M dS, Y, H:i:s",5678)."<br>";
// this will display Thursday Jan 01st, 1970, 03:34:38 in GMT
?>

There is also a related gmdate() function, which is the same as date(), the difference being that it returns the Greenwich Mean Time.

Calculations with time() and mktime()

Returning the current timestamp is easy with the time() function:

<?php
echo time();
?>

This little script displayed “1062992346” for me. You can see how many seconds have passed since I wrote this by comparing the results you receive. This provides you with an idea of how to perform date and time arithmetic. By subtracting the two timestamps, you can see how many seconds have elapsed, and once you have that, you can convert it into more friendly formats with some of the other functions provided by PHP.

Working from the opposite direction, we can generate a timestamp with the mktime() function. There will be instances when you will need to generate a timestamp based on a date/time in another format, such as those passed to you from another source, or from your database. The mktime() function will accept up to seven parameters, all of which are integers:

mktime(hour,minute,second,month,day,year,is_dst)

You will notice that the order of the parameters is somewhat strange, and any of the parameters can be left out – those that are left out will be assumed from the current date. The last parameter is used for daylight saving time (1 for yes, 0 for no, -1 for PHP to calculate).

<?php
// timestamp for 13:56:04 on 18 Jun 2003
echo mktime(13,56,04,06,18,2003)."<br>";
echo date("M d Y, H:i:s",mktime(13,56,04,06,18,2003));
?>

The mktime() function makes date and time calculations easy through the use of integer parameters, and the ability to move out of a date scope. If you want to calculate a timestamp eighteen days beyond the one we generated in the above example, simply add eighteen to the days integer. Even though this produces 36, PHP will automatically work it out as if it was the 6th of July:

<?php
// timestamp for 13:56:04 on 18 Jun 2003
echo mktime(13,56,04,06,18,2003)."<br>";
echo date("M d Y, H:i:s",mktime(13,56,04,06,18,2003))."<br>";

// timestamp for 13:56:04 on 18 Jun 2003 + 18 days
echo mktime(13,56,04,06,36,2003)."<br>";
echo date("M d Y, H:i:s",mktime(13,56,04,06,36,2003))."<br>";
?>

As you can imagine, calculating dates in the past is just as simple – just subtract the integer value from the relevant parameter.

The related PHP function gmmktime(), is identical to mktime(), the difference being that the passed parameters represent a Greenwich Mean Time date.

The getdate() and localtime() Functions

The date function is useful for returning a date, but not the best solution for returning data that is useful for your applications.

array getdate ( [int timestamp])
The PHP function getdate() returns an associative array containing the following elements:

“seconds” seconds
“minutes” minutes
“hours” hours
“mday” day of the month
“wday” day of the week, numeric : from 0 as Sunday up to 6 as Saturday
“mon” month, numeric
“year” year, numeric
“yday” day of the year, numeric; i.e. “299”
“weekday” day of the week, textual, full; i.e. “Friday”
“month” month, textual, full; i.e. “January”
“0” timestamp

The getdate() function retrieves the current time on default, but a timestamp value can also be evaluated by this function:

<?php
$today = getdate(); 
foreach($today as $key=>$val) {
 echo "$key: $val";
}
// each element of the array is dumped to the screen
?>

That code snippet will produce output much like the following:

seconds => 8
minutes => 53
hours => 10
mday => 8
wday => 1
mon => 9
year => 2003
yday => 250
weekday => Monday
month => September
0 => 1063032788

You can use the localtime() function as alternative to the getdate() function:

array localtime ( [int timestamp [, bool is_associative]])

The localtime() function returns an alternative array to getdate(). It is OS dependant, and uses the underlying C function call. It takes an optional two parameters:

timestamp (defaults to current time)
associative or numeric array indicator (0 for numeric, 1 for associative)

<?php
$today = localtime(time(),1);     
// we have indicated we want the associative array structure
foreach($today as $key=>$val) {
 echo "$key => $val<br>";
}
// each element of the array is dumped to the screen
?>

This code snippet will produce the following results, based on my timestamp value:

tm_sec => 30
tm_min => 59
tm_hour => 10
tm_mday => 8
tm_mon => 8
tm_year => 103
tm_wday => 1
tm_yday => 250
tm_isdst => 1

Note that the default array indicator is 0. Using that indicator, our output would have looked like this:

0 => 30
1 => 59
2 => 10
3 => 8
4 => 8
5 => 103
6 => 1
7 => 250
8 => 1

Note that you should take care in using this function when using the results in mktime(). The localtime() function returns months as 0 to 11, but mktime uses months as 1 to 12. Ensure you compensate for this if you plan on using these functions together.

Add a Comment

Your email address will not be published. Required fields are marked *

ABOUT CODINGACE

My name is Nohman Habib and I am a web developer with over 10 years of experience, programming in Joomla, Wordpress, WHMCS, vTiger and Hybrid Apps. My plan to start codingace.com is to share my experience and expertise with others. Here my basic area of focus is to post tutorials primarily on Joomla development, HTML5, CSS3 and PHP.

Nohman Habib

CEO: codingace.com

Request a Quote









PHP Code Snippets Powered By : XYZScripts.com