Compare Dates

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 asserts true? After all 15 is greater than 10 and M(arch) occurs after A(pril) on the alphabet.


Using the Ymd Format

If the date were formatted as Year Month Day in 4 digit year and 2 digit month and 2 digit day then we could make a direct comparison.
I.e 20120410 is greater than 20120315
This would be useful if we needed to see if today was not passed a certain date (an expiry date for instance).

$today = date('Ymd');
if($today > 20120410)
  echo 'Something has expired';

Using the TimeStamp

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.

$today = mktime();
$expire_date = mktime(0, 0, 0, date('m')  , date('d')+1, date('Y'));
 
if($today > $expire_date)
  echo 'Something has expired';

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

Comments

Add new comment

Plain text

  • No HTML tags allowed.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.
By submitting this form, you accept the Mollom privacy policy.