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 PC World newsletter!

Error: Please check your email address.

Our Back to Business guide highlights the best products for you to boost your productivity at home, on the road, at the office, or in the classroom.

Keep up with the latest tech news, reviews and previews by subscribing to the Good Gear Guide newsletter.

Gavin Sherry

PC World
Show Comments

Essentials

Lexar® JumpDrive® S57 USB 3.0 flash drive

Learn more >

Microsoft L5V-00027 Sculpt Ergonomic Keyboard Desktop

Learn more >

Mobile

Lexar® JumpDrive® S45 USB 3.0 flash drive 

Learn more >

Exec

Audio-Technica ATH-ANC70 Noise Cancelling Headphones

Learn more >

Lexar® JumpDrive® C20c USB Type-C flash drive 

Learn more >

Lexar® Professional 1800x microSDHC™/microSDXC™ UHS-II cards 

Learn more >

HD Pan/Tilt Wi-Fi Camera with Night Vision NC450

Learn more >

Budget

Back To Business Guide

Click for more ›

Most Popular Reviews

Latest News Articles

Resources

PCW Evaluation Team

Azadeh Williams

HP OfficeJet Pro 8730

A smarter way to print for busy small business owners, combining speedy printing with scanning and copying, making it easier to produce high quality documents and images at a touch of a button.

Andrew Grant

HP OfficeJet Pro 8730

I've had a multifunction printer in the office going on 10 years now. It was a neat bit of kit back in the day -- print, copy, scan, fax -- when printing over WiFi felt a bit like magic. It’s seen better days though and an upgrade’s well overdue. This HP OfficeJet Pro 8730 looks like it ticks all the same boxes: print, copy, scan, and fax. (Really? Does anyone fax anything any more? I guess it's good to know the facility’s there, just in case.) Printing over WiFi is more-or- less standard these days.

Ed Dawson

HP OfficeJet Pro 8730

As a freelance writer who is always on the go, I like my technology to be both efficient and effective so I can do my job well. The HP OfficeJet Pro 8730 Inkjet Printer ticks all the boxes in terms of form factor, performance and user interface.

Michael Hargreaves

Windows 10 for Business / Dell XPS 13

I’d happily recommend this touchscreen laptop and Windows 10 as a great way to get serious work done at a desk or on the road.

Aysha Strobbe

Windows 10 / HP Spectre x360

Ultimately, I think the Windows 10 environment is excellent for me as it caters for so many different uses. The inclusion of the Xbox app is also great for when you need some downtime too!

Mark Escubio

Windows 10 / Lenovo Yoga 910

For me, the Xbox Play Anywhere is a great new feature as it allows you to play your current Xbox games with higher resolutions and better graphics without forking out extra cash for another copy. Although available titles are still scarce, but I’m sure it will grow in time.

Featured Content

Latest Jobs

Don’t have an account? Sign up here

Don't have an account? Sign up now

Forgot password?