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!

Or

Sign up to gain exclusive access to email subscriptions, event invitations, competitions, giveaways, and much more.

Membership is free, and your security and privacy remain protected. View our privacy policy before signing up.

Error: Please check your email address.
Keep up with the latest tech news, reviews and previews by subscribing to the Good Gear Guide newsletter.

Gavin Sherry

PC World
Show Comments

Cool Tech

Bang and Olufsen Beosound Stage - Dolby Atmos Soundbar

Learn more >

Toys for Boys

Sony WF-1000XM3 Wireless Noise Cancelling Headphones

Learn more >

ASUS ROG, ACRONYM partner for Special Edition Zephyrus G14

Learn more >

Nakamichi Delta 100 3-Way Hi Fi Speaker System

Learn more >

Family Friendly

Mario Kart Live: Home Circuit for Nintendo Switch

Learn more >

Philips Sonicare Diamond Clean 9000 Toothbrush

Learn more >

Stocking Stuffer

SunnyBunny Snowflakes 20 LED Solar Powered Fairy String

Learn more >

Teac 7 inch Swivel Screen Portable DVD Player

Learn more >

Christmas Gift Guide

Click for more ›

Brand Post

Shining a light on creativity

MSI has long pushed the boundaries of invention with its ever-evolving range of laptops but it has now pulled off a world first with the new MSI Creative 17.

Most Popular Reviews

Latest Articles

Resources

PCW Evaluation Team

Tom Pope

Dynabook Portégé X30L-G

Ultimately this laptop has achieved everything I would hope for in a laptop for work, while fitting that into a form factor and weight that is remarkable.

Tom Sellers

MSI P65

This smart laptop was enjoyable to use and great to work on – creating content was super simple.

Lolita Wang

MSI GT76

It really doesn’t get more “gaming laptop” than this.

Jack Jeffries

MSI GS75

As the Maserati or BMW of laptops, it would fit perfectly in the hands of a professional needing firepower under the hood, sophistication and class on the surface, and gaming prowess (sports mode if you will) in between.

Taylor Carr

MSI PS63

The MSI PS63 is an amazing laptop and I would definitely consider buying one in the future.

Christopher Low

Brother RJ-4230B

This small mobile printer is exactly what I need for invoicing and other jobs such as sending fellow tradesman details or step-by-step instructions that I can easily print off from my phone or the Web.

Featured Content

Product Launch Showcase

Don’t have an account? Sign up here

Don't have an account? Sign up now

Forgot password?