brenlei.com

PHP tutorials

Question:

How can I compare dates to see which one occurs first?

Answer:

Consider these two dates (for the same year). 15th March and 10th April. There should be no argument that 10th of April occurs AFTER the 15th of March, but how do we write a comparison that results in true for it? After all 15 is greater than 10 and M(arch) occurs after A(pril) on the alphabet.

Technique 1

If the date were formatted as Year Month Day in 4 digit year and 2 digit month and day then we could make a direct comparison.

I.e  20060410 is greater than 20060315

This would be useful if we needed to see if today was not passed a certain date (an expiry date for instance).

Example:
$today = date('Ymd');
if($today > 20060410)
  echo 'Something has expired';

Technique 2

The other technique is to convert both dates into UNIX timestamps which basically records the number of seconds that has elapsed since January 1st 1970. The conversion can be done with the mktime function as shown in the example below.

Example:
$today = mktime();
$expire_date = mktime(0, 0, 0, date('m')  , date('d')+1, date('Y'));

if($today > $expire_date)
  echo 'Something has expired';
Additional Notes:

We could have used $today = date('U'); instead of $today = mktime(); if we wanted. They both return the same result.

PHP Reference Manual

date - Returns a formatted date

mktime - Returns a UNIX timestamp

Dates

How do you calculate the difference between two dates?
Learn a few techniques in date arithmetic to find the elapsed time between two dates.

Comments or questions relating to this article have been disabled. They will be back soon.