Using Date and Time Functions in PHP

Using Date and Time Functions in PHP
The following sections introduce you to the date- and time-related functions specifically in PHP. Try out each listing for yourself to see how simple and powerful these functions can be.

ارایه درگاه پرداخت ePayBank.ir برای برنامه نویسان PHP سایتهای اینترنتی ایرانی

تبلیغات اینترنتی خدمات و نیازمندیهای خود را در سایت MyCityAd.ir بصورت ستاره دار درج نمایید

آموزش خصوصی و تدریس خصوصی PHP را با تهیه بسته آموزشی طراحی سایت گروه طراحان آریاکدرز بنشانی Webdesign.epaybank.ir بصورت کاربردی و عملی تجربه خواهید کرد.

Getting the Date with time()
PHP’s time() function gives you all the information you need about the current date and time. It requires no arguments and returns an integer. For us humans, the returned number is a little hard on the eyes, but it’s extremely useful nonetheless.

echo time();
// sample output: 1141137255
// this represents February 28, 2006 at 06:33AM

The integer returned by time() represents the number of seconds elapsed since midnight GMT on January 1, 1970. This moment is known as the UNIX epoch, and the number of seconds that have elapsed since then is referred to as a time stamp. PHP offers excellent tools to convert a time stamp into a form that humans are comfortable with. Even so, you may think, “Isn’t a time stamp a needlessly convoluted way of storing a date?” In fact, the opposite is true. From just one number, you can extract enormous amounts of information. Even better, a time stamp can make date arithmetic much easier than you might imagine.

Think of a homegrown date system in which you record days of the month as well as months and years. Now imagine a script that must add one day to a given date. If this date happened to be 31 December 1999, rather than adding 1 to the date, you’d have to write code to set the day of the month to 1, the month to January, and the year to 2000. Using a time stamp, you need only add a day’s worth of seconds (60 * 60 * 24, or 86400) to your current figure and you’re done. You can convert this new figure into something friendlier, at your leisure.

Converting a Time Stamp with getdate()
Now that you have a time stamp to work with, you must convert it before you present it to the user. getdate() optionally accepts a time stamp and returns an associative array containing information about the date. If you omit the time stamp, getdate() works with the current time stamp as returned by time(). Table 10.3 lists the elements contained in the array returned by geTDate().

Table 10.3. The Associative Array Returned by getdate() Key
Description
Example

seconds
Seconds past the minute (059)
43

minutes
Minutes past the hour (059)
30

hours
Hours of the day (023)
8

mday
Day of the month (131)
9

wday
Day of the week (06)
1

mon
Month of the year (112)
8

year
Year (4 digits)
2004

yday
Day of the year (0365)
221

weekday
Day of the week (name)
Monday

month
Month of the year (name)
August

0
Time stamp
1092065443

Listing 10.4 uses getdate() in line 2 to extract information from a time stamp, employing a foreach statement to print each element (line 3). You can see typical output in Figure 10.5. The getdate() function returns the date according to the local time zone.

Figure 10.5. Using getdate().

[View full size image]

Listing 10.4. Acquiring Date Information with getdate()
1: <?php
2: $date_array = getdate(); // no argument passed so today’s date will be used
3: foreach ($date_array as $key => $val) {
4: echo “$key = $val<br>”;
5: }
6: ?>
7: <hr/>
8: <?php 9: echo “<p>Today’s date: “.$date_array[‘mon’].”/”.$date_array[‘mday’].”/”.
10: $date_array[‘year’].”</p>”;
11: ?>

Converting a Time Stamp with date()
You can use geTDate() when you want to work with the elements that it outputs. Sometimes, though, you want to display the date as a string. The date() function returns a formatted string that represents a date. You can exercise an enormous amount of control over the format that date() returns with a string argument that you must pass to it. In addition to the format string, date() optionally accepts a time stamp. Table 10.4 lists some of the codes that a format string can contain. You can find the complete list at http://www.php.net/date. Any other data you include in the format string passed to date() is included in the return value.

Table 10.4. Some Format Codes for Use with date() Format
Description
Example

a
am or pm (lowercase)
am

A
AM or PM (uppercase)
AM

d
Day of month (number with leading zeroes)
28

D
Day of week (three letters)
Tue

e
Timezone identifier
America/Los_Angeles

F
Month name
February

h
Hour (12-hour formatleading zeroes)
06

H
Hour (24-hour formatleading zeroes)
06

g
Hour (12-hour formatno leading zeroes)
6

G
Hour (24-hour formatno leading zeroes)
6

i
Minutes
45

j
Day of the month (no leading zeroes)
28

l
Day of the week (name)
Tuesday

L
Leap year (1 for yes, 0 for no)
0

m
Month of year (numberleading zeroes)
2

M
Month of year (three letters)
Feb

n
Month of year (numberno leading zeroes)
2

s
Seconds of hour
26

S
Ordinal suffix for the day of the month
th

r
Full date standardized to RFC 822
Tue, 28 Feb 2006 06:45:26

(http://www.faqs.org/rfcs/rfc822.html)
-0800

U
Time stamp
1141137926

y
Year (two digits)
06

Y
Year (four digits)
2006

z
Day of year (0365)
28

Z
Offset in seconds from GMT
-28800

Listing 10.5 puts a few of these format codes to the test.

Listing 10.5. Formatting a Date with date()
1: <?php
2: $time = time(); //stores the exact timestamp to use in this script
3: echo date(“m/d/y G:i:s e”, $time);
4: echo “<br/>”;
5: echo “Today is “;
6: echo date(“jS \o\f F Y, \a\\t g:ia \i\\n e”, $time);
7: ?>

Listing 10.5 calls date() twice: the first time on line 3 to output an abbreviated date format, and the second time on line 6 for a longer format. Save the text of this listing in a file called datetest.php and open it in your web browser. Your date will differ from the following, obviously, but here’s some sample output:

02/28/06 6:45:26 America/Los_Angeles

Today is the 28th of February 2006, at 6:45am in America/Los_Angeles. Although the format string looks arcane, it’s easy to build. If you want to add a string that contains letters that are also format codes to the format, you can escape them by placing a backslash (\) in front of them. For characters that become control characters when escaped, you must escape the backslash that precedes them. For example, \t is a format code for a tab, so to ensure that the tab prints, use \\t as in the example in Listing 10.5.

Another example is in the context of a word you are adding to a string; for example, the. The word the is made up of three format codes, so all must be escaped:

<?php
echo date(“l \\t\h\e jS”);
//prints Tuesday the 28th
?>

Also note that the date() function returns information according to your local time zone. If you want to format a date in GMT, you use the gmdate() function, which works in exactly the same way.

Creating Time Stamps with mktime()
You can already get information about the current time, but you cannot yet work with arbitrary dates. mktime() returns a time stamp that you can then use with date() or getdate(). mktime() accepts up to six integer arguments in the following order:

Hour

Minute

Second

Month

Day of month

Year

Listing 10.6 uses mktime() to get a time stamp that we then use with the date() function.

Listing 10.6. Creating a Time Stamp with mktime()
1: <?php
2: // make a timestamp for Feb 28 2006 at 6:48 am
3: $ts = mktime(6, 48, 0, 2, 28, 2006);
4: echo date(“m/d/y G:i:s e”, $ts);
5: echo “<br/>”;
6: echo “The date is “;
7: echo date(“jS \o\f F Y, \a\\t g:ia \i\\n e”, $ts );
8: ?>

We call mktime() on line 3 and assign the returned time stamp to the $ts variable. We then use the date() function on lines 4 and 7 to output formatted versions of the date using $ts. You can choose to omit some or all the arguments to mktime(), and the value appropriate to the current time is used instead. mktime() also adjusts for values that go beyond the relevant range, so an hour argument of 25 translates to 1:00 a.m. on the day after that specified in the month, day, and year arguments.

Save the text of this listing in a file called mktimetest.php and open it in your web browser. You should see

02/28/06 6:48:00 America/Los_Angeles
The date is 28th of February 2006, at 6:48am in America/Los_Angeles

Testing a Date with checkdate()
You might need to accept date information from user input. Before you work with a user-entered date or store it in a database, make sure that the date is valid. checkdate() accepts three integers: month, day, and year. checkdate() returns true if the month is between 1 and 12, the day is acceptable for the given month and year (accounting for leap years), and the year is between 0 and 32767. Be careful, though: A date might be valid but not acceptable to other date functions. For example, the following line returns TRue:

checkdate(4, 4, 1066)

If you were to attempt to build a date with mktime() using these values, you’d end up with a time stamp of -1. As a rule of thumb, don’t use mktime() with years before 1902, and be cautious of using date functions with any date before 1970 because negative numbers are not valid dates. Because the UNIX epoch began January 1, 1970, anything before that is an invalid (negative) time stamp.