Working with Dates and Times In this lesson you will learn how to store, display, and manipulate date and time values in PHP... Unix Timestamp Format The Unix timestamp format is an in
Trang 1Summary
In this lesson you have learned the basics of regular expressions If you want to find out more, you can refer to Sams Teach Yourself Regular Expressions in 10 Minutes by Ben Forta
In the next lesson you will learn how to handle date and time values in PHP
Lesson 9 Working with Dates and Times
In this lesson you will learn how to store, display, and manipulate date and time values in PHP
Trang 2Date Formats
PHP does not have a native date data type, so in order to store date values in a script, you must first decide on the best way to store these values
Do-It-Yourself Date Formats
Although you often see dates written in a structured format, such as 05/03/1974 or 2001-12-31, these are not ideal formats for working with date values However, the latter of these two is more suitable than the first because the order of its
components is from most significant (the year) to the least significant (the day), so values can be compared using the usual PHP operators
As a string, 2002-01-01 is greater than 2001-12-31, but because
comparisons are performed more efficiently on numbers than on strings, this could
be written better as just 20020201, where the format is YYYYMMDD This format can be extended to include a time portionagain, with the most significant elements firstas YYYYMMDDHHMMSS, for example
However, date arithmetic with this format is nearly impossible While you can add one to 20040501, for instance, and find the next day in that month, simply
adding one to 20030531 would result in a nonsense date of May 32
Unix Timestamp Format
The Unix timestamp format is an integer representation of a date and time It is a value that counts the number of seconds since midnight on January 1, 1970
The Unix Epoch A timestamp with integer value zero represents
precisely midnight, Greenwich Mean Time (GMT), on January 1,
1970 This date is known as the Unix Epoch
Right now, we have a 10-digit date and time timestamp To find the current
timestamp, you use the time function:
echo time();
Trang 3The Unix timestamp format is useful because it is very easy to perform
calculations on because you know that the value always represents a number of seconds For example, you can just add 3,600 to a timestamp value to increase the time by one hour or add 86,400 to add one daybecause there are 3,600 seconds in
an hour and 86,400 seconds in a day
One drawback, however, is that the Unix timestamp format cannot handle dates prior to 1970 Although some systems may be able to use a negative timestamp value to count backward from the Epoch, this behavior cannot be relied on
Timestamps are good for representing contemporary date values, but they may not always be suitable for handling dates of birth or dates of historical significance You should consider what values you will be working with when deciding whether
a timestamp is the correct format to use
Timestamp Limitations The maximum value of a Unix timestamp
depends on the system's architecture Most systems use a 32-bit
integer to store a timestamp, making the latest time it can
represent 3:14am on January 19, 2038
Trang 4Working with Timestamps
There are times when using your own date format is beneficial, but in most cases a timestamp is the best choice Let's look at how PHP interacts with the timestamp date format
Formatting Dates
In Lesson 1, "Getting to Know PHP," you used the date function to display the current date by passing a format string as the argument, such as in the following example:
echo date("j F Y H:i:s");
The date displayed looks something like this:
12 November 2004 10:23:55
The optional second argument to date is a timestamp value of the date that you want to display For example, to display the date when a timestamp first requires a 10-digit number, you could use the following:
echo date("j F Y H:I:s", 1000000000);
The list of format codes for the date function is shown in Table 9.1
Table 9.1 Format Codes for date
Code Description
a Lowercase am or pm
A Uppercase AM or PM
d Two-digit day of month, 0131
D Three-letter day name, MonSun
Trang 5F Full month name, JanuaryDecember
g 12-hour hour with no leading zero, 112
G 24-hour hour with no leading zero, 023
h 12-hour hour with leading zero, 0112
H 24-hour hour with leading zero, 0023
I Minutes with leading zero, 0059
j Day of month with no leading zero, 131
l Full day name, MondaySunday
m Month number with leading zeros, 0112
M Three letter month name, JanDec
n Month number with no leading zeros, 112
s Seconds with leading zero, 0059
S Ordinal suffix for day of month, st, nd, rd, or th
w Number of day of week, 06, where 0 is Sunday
W Week number, 053
y Two-digit year number
Y Four-digit year number
z Day of year, 0365
Creating Timestamps
Don't worry; you don't have to count from January 1, 1970, each time you want to calculate a timestamp The PHP function mktime returns a timestamp based on given date and time values
The arguments, in order, are the hour, minute, second, month, day, and year The following example would assign $timestamp the timestamp value for 8 a.m on December 25, 2001:
$timestamp = mktime(8, 0, 0, 12, 25, 2001);
Trang 6The Unix timestamp format counts from January 1, 1970, at midnight GMT The mktime function returns a timestamp relative to the time zone in which your system operates For instance, mktime would return a timestamp value 3,600 higher when running on a web server in Texas than on a machine in New York with the same arguments
Daylight Saving Time If you are only concerned with the date part
of a timestamp, the first three arguments to mktime only matter if
they are close to midnight at a time of the year when daylight
saving time is a factor
For instance, when the clocks are moved back one hour, that day
is only 23 hours long Adding 86,400 seconds to a timestamp that
represents midnight on that day will actually move the day part of
the timestamp forward two days You can use midday instead of
midnight as the time element to avoid these issues
Greenwich Mean Time To obtain timestamp values that are
always relative to GMTthe time in London when there is no
daylight saving time adjustmentyou use gmmktime instead of
mktime
The mktime function is forgiving if you supply it with nonsense arguments, such
as a day of the month that doesn't exist For instance, if you try to calculate a timestamp for February 29 in a non-leap year, the value returned will actually represent March 1, as the following statement confirms:
echo date("d/m/Y", mktime(12, 0, 0, 2, 29, 2003));
You can exploit this behavior as a way of performing date and time arithmetic Consider the following example, which calculates and displays the date and time
37 hours after midday on December 30, 2001:
$time = mktime(12 + 37, 0, 0, 12, 30, 2001);
echo date("d/m/Y H:i:s", $time);
Trang 7By simply adding a constant to one of the arguments in mktime, you can shift the timestamp value returned by that amount The date and time display as follows: 01/01/2002 01:00:00
The value returned in this example has correctly shifted the day, month, year, and hour values, taking into account the number of days in December and that
December is the last month of the year
Converting Other Date Formats to Timestamps
If you have a date stored in a format like DD-MM-YYYY, it's a fairly simple process
to convert this to a timestamp by breaking up the string around the hyphen
character The explode function takes a delimiter argument and a string and returns an array that contains each part of the string that was separated by the given delimiter
The following example breaks a date in this format into its components and builds
a timestamp from those values:
$date = "03-05-1974";
$parts = explode("/", $date);
$timestamp = mktime(12, 0, 0,
$parts[1], $parts[0], $parts[2]);
For many date formats, there is an even easier way to create a timestampusing the function strtotime The following examples all display the same valid
timestamp from a string date value:
$timestamp = strtotime("3 May 04");
$timestamp = strtotime("3rd May 2004");
$timestamp = strtotime("May 3, 2004");
$timestamp = strtotime("3-may-04");
$timestamp = strtotime("2004-05-03");
$timestamp = strtotime("05/03/2004");
Note that in the last examples, the date format given is MM/DD/YYYY, not
Trang 8DD/MM/YYYY You can find the complete list of formats that are acceptable to strtotime at www.gnu.org/software/tar/manual/html_chapter/tar_7.html
Getting Information About a Timestamp
You can use the date function to return part or all of the date that a timestamp represents as a formatted string, but PHP also provides the geTDate function, which returns useful values from a timestamp
Taking a single timestamp argument, geTDate returns an associative array that contains the indexes shown in Table 9.2
Table 9.2 Key Elements Returned by geTDate
Key Description
seconds Seconds, 059
minutes Minutes, 059
hours Hours, 023
mday Day of the month, 031
wday Day of the week, 06, where 0 is Sunday
yday Day of the year, 0365
mon Month number, 012
year Four-digit year number
weekday Full day name, SundaySaturday
month Full month name, JanuaryDecember
The following example uses getdate to determine whether the current date falls
on a weekday or weekend:
$now = getdate();
switch ($now[wday]) {
case 0: // Sunday
case 6: // Saturday
Trang 9echo "It's the weekend";
break;
default: echo "It's a weekday";
}
Note that when getdate is called without a timestamp argument, it returns an array that contains the elements in Table 9.2 for the current time