Dates and time in PHP

Dates and time form an important part of many sophisticated PHP applications. From simply displaying the date for a user to validating dates and times in user-supplied input, PHP developers have a wealth of functions to solve all manner of problems.

Python vs. PHP: Choosing your next project's language

Complexity of dates and time

Unfortunately, our modern date and time systems were not designed with simple mathematics in mind. Some of the complexities one must take into account when handling dates are that not all months have the same number of days, some years have an extra day, the day of the week does not correspond to a given day of the month, and dates can be expressed in many formats (2003-03-01, 1/3/03 or '1st of march, this year'). Some complexities with handling times include dealing with time zones, time changes due to daylight savings, and converting times into different units (convert 5:15 p.m. to seconds, for example).

To simplify the situation, UNIX operating systems (in particular) treat dates and times in terms of the number of seconds since 1/1/1970. This is often called 'seconds since the epoch' or a (UNIX) timestamp. This system allows developers to calculate dates and times using integers - significantly easier than subtracting or adding days, months and hours. Many of the PHP date and time functions make use of this system.

Convert dates and times to seconds

Converting dates and times to the number of seconds since the epoch with PHP is simple, as the following script shows:

01 <?
02 $today = time();
03 $jan = mktime(12,0,0,1,1,2003);
04 $secs = $today - $jan;
05 echo "Number of seconds since midday 1/1/2003: $secs\n";
06 $days = (int)($secs/(60 * 60 * 24));
07 echo "Number of days since 1/1/2003: $days\n";
08 ?>

On line 02, the script generates the current number of seconds since the epoch using the time() function. The next line does the same, but for midday on 1 January 2003. We do this by using the mktime() - or make time - function. The arguments run as follows: the hour, the number of minutes, the number of seconds, the month, the day of the month and finally the year.

Line 04 calculates the result with simple mathematics, and line 05 reports the result to the user. Line 06 divides $secs by the number of seconds in a day. Note the (int) in front of this calculation: this casts the result to an integer - that is, rounds it from a decimal to a natural number. Line 07 reports the result to the user.

Validating dates

When dealing with user-supplied data, it is important to verify that the date is valid. For example, a user may accidentally submit the date 31 February 2003, which is invalid because this date doesn't exist. PHP allows developers to validate dates. Consider the following:

01 <?
02 $year = $HTTP_POST_VARS["year"];
03 $month = $HTTP_POST_VARS["month"];
04 $day = $HTTP_POST_VARS["day"];
05 if(checkdate($month,$day,$year)) {
06	 $secs = mktime(0,0,0,$month,$day,$year);
07 } else {
08	 echo "Invalid date";
09 }
10 ?>

Lines 02, 03 and 04 define local variables from a user-submitted form. Line 05 calls checkdate() to verify that the supplied data is valid. If it is, checkdate() returns true; otherwise, false.

Getting more from timestamps

PHP allows developers to convert UNIX timestamps to highly formatted, human-readable dates. Using the date() function, any number of different date and time representations can be created. For example:

01 <?
02 $d1 = date("l, jS F Y",mktime(0,0,0,1,1,2003));
03 $d2 = date("G:i:s");
04 ?>

Line 02 creates a human-readable date 'Wednesday, 1st January 2003'. date() formats the converted timestamp in this way based on the modifiers passed in the first argument. The modifier 'l' returns the day of the week, 'j' returns the day of the month, 'S' returns one of 'st', 'nd', 'rd' or 'th' depending on the day of the month, 'F' returns the month and 'Y' returns the year.

Line 03 creates a human-readable time of the format hours:minutes:seconds. The modifier 'G' returns hours in 24 hour format: 'i' is minutes and 's' is seconds. A second argument has been omitted and, as such, date() uses the current timestamp. For more information and details of other modifiers see http://www.php.net/manual/en/function.date.php.

Dates and times can be a complex issue, but by using established conventions and built-in PHP functions, developers can add simple but sophisticated functionality to their applications.

Join the newsletter!

Error: Please check your email address.
Rocket to Success - Your 10 Tips for Smarter ERP System Selection
Keep up with the latest tech news, reviews and previews by subscribing to the Good Gear Guide newsletter.

Gavin Sherry

PC World
Show Comments

Most Popular Reviews

Latest Articles

Resources

PCW Evaluation Team

Ben Ramsden

Sharp PN-40TC1 Huddle Board

Brainstorming, innovation, problem solving, and negotiation have all become much more productive and valuable if people can easily collaborate in real time with minimal friction.

Sarah Ieroianni

Brother QL-820NWB Professional Label Printer

The print quality also does not disappoint, it’s clear, bold, doesn’t smudge and the text is perfectly sized.

Ratchada Dunn

Sharp PN-40TC1 Huddle Board

The Huddle Board’s built in program; Sharp Touch Viewing software allows us to easily manipulate and edit our documents (jpegs and PDFs) all at the same time on the dashboard.

George Khoury

Sharp PN-40TC1 Huddle Board

The biggest perks for me would be that it comes with easy to use and comprehensive programs that make the collaboration process a whole lot more intuitive and organic

David Coyle

Brother PocketJet PJ-773 A4 Portable Thermal Printer

I rate the printer as a 5 out of 5 stars as it has been able to fit seamlessly into my busy and mobile lifestyle.

Kurt Hegetschweiler

Brother PocketJet PJ-773 A4 Portable Thermal Printer

It’s perfect for mobile workers. Just take it out — it’s small enough to sit anywhere — turn it on, load a sheet of paper, and start printing.

Featured Content

Product Launch Showcase

Latest Jobs

Don’t have an account? Sign up here

Don't have an account? Sign up now

Forgot password?