The Tricky.net

Compare dates with PHP
Compare dates with PHP

I read a lot of people having trouble while comparing dates with php, trying to guess with some substring functions if date A is before or after date B. I would like to introduce some very convenient functions which simplify greatly your life.

Let's begin with the definition of a timestamp : it's simply the number of seconds elapsed since the 1st january 1970. Yes, the number of seconds, it seems maybe a bit odd, but you discover then that these timestamps are very practical to manipulate: comparing dates, adding some days to a date, differences between dates, all these can be easily done with timestamps.

Obviously, you think: and dates before 1970??? Depends of the platform on which runs PHP: on Windows, you cannot have negative timestamps, and it's the same problem with some linux distribution. You'll have to try to know, but if you get false, -1 or "1 jan 1970" as result of the function returning a timestamp with a correct date given, it's bad news. If it's ok, know you can normally handle dates between 13 december 1901 and 19 january 2038.

strtotime

You have in php some great functions to convert your human readable dates to timestamps.

The first magic function is called strtotime (string to time) : give it your date, you get a UNIX timestamp! Let's see some examples:

 
echo strtotime('2008-04-12 13:24');
echo strtotime('12 april 2008 13:24');
echo strtotime('12.04.2008 13:24');
 

And more powerfull, strtotime can recognize some keywords:

 
echo strtotime('now');
echo strtotime('+4 days');
echo strtotime('+1 month');
echo strtotime('next monday');
echo strtotime('+2 weeks 3 days 4 hours 23 minutes');
 

The second argument of strtotime is a timestamp, and its default value is the actual timestamp (time()). So echo strtotime('+4 days') is relative to the current time. Of course you can also give strtotime your mysql date! (Note you can also use the mysql function UNIX_TIMESTAMP, which use a bit more ressources).

To compare dates, it's now just a detail:

 
// your first date coming from a mysql database (date fields) 
$dateA = '2008-03-01 13:34'; 
// your second date coming from a mysql database (date fields) 
$dateB = '2007-04-14 15:23'; 
if(strtotime($dateA) > strtotime($dateB)){ 
    // bla bla 
}

Better than substring, isn't it ?!

Here is just another example, not relative to current date but to a particular date:

strtotime('23 hours ago', strtotime('2005-04-13 14:00'));

This mean 23 hours ago relatively to the second given date, which must be a timestamp.

mktime()

Another easy and useful function is the famous mktime(). It returns also a UNIX timestamp:
int mktime(hour, minute, second, month, day, year);

Every argument is optionnal, mktime() will return the current UNIX timestamp.
Let's see an example:
date('r', mktime(2, 24, 0, 3, 12, 2008);

Be aware not to prefix the values with '0' (like '02'), PHP will treat it as an octal value (default PHP behaviour)!

And what if you go over the number of days in the month for example? The function will correct the values for you: if you give it '03-33-2008', you will get the timestamp of the date '04-2-2008'! That's very interesting for us, because we don't have to care anymore about being in the range for the day, the month, ...
A concrete example where we use this feature (inspired from php.net)
  1. $nbDaysInYear = 365;
  2. $yearArray = array();
  3. while($nbDaysInYear > 0){
  4. $yearArray[] = date("Y-m-d", mktime(0, 0, 0, 1, $nbDaysInYear, 2008);
  5. $nbDaysInYear--;
  6. }

This code snippet will fill an array with all the date of the year 2008. See how the $nbDaysInYear variable varies: at first iteration, we have on line 4:
 
    $yearArray[] = date("Y-m-d", mktime(0,0,0,1,365,2008);
 

No problem for mktime, it will find calculate what date in the year it is!

Conclusion

With these function you should now be able to build all the basic functions you need for dates. Remember the basics: get a timestamp with strtotime or mktime, then convert it to the format you want with the date function. And remember you cannot handle dates beyond the limit dates given by the platform on which PHP runs.
And about dates with mySQL ? see this article

Comments
Add New Search RSS
khai (203.106.236.xxx) 09-12-2009 02:55:54

thanks for the tutorial
Thank you,
Mohammed El Qadi (41.130.76.xxx) 19-11-2009 11:34:34

, thank you.
It helped me alot.
adrian (87.74.16.xxx) 27-08-2009 10:40:08

Thanks, very usefull, I hate working with dates, this was just what I was
looking for
Erik (24.60.254.xxx) 28-02-2009 20:57:52

For some reason the "hours ago" example isn't working correctly.


I do the following code:


echo strtotime('2009-02-28 1300')."";
echo strtotime('2
hours ago', '2009-02-28 1300');


The values I
get are:

1235844000
-5191

I'd expect the second value to be
1235844000 minus 2 hours...
sebastien (Administrator) 07-09-2009 14:08:58

Sorry, there is a mistake in the example. The second argument of strtotime
must be a timestamp, not a string. So you write:
strtotime('23 hours ago', strtotime('2005-04-13 14:10'));
I corrected the
article.
sebastien (Administrator) 22-06-2008 18:18:57

Thanks for your comment. You're right, I did not notice the readers that
these function don't always work with dates between 1970 and 2038. It depends actually of the
platform on which runs PHP.
I corrected this in the article.

Milke (210.86.215.xxx) 22-06-2008 06:38:23

Your article is somehow misleading and does not go into the real PHP/Unix
problem when comparing dates.
If your dates are beyond the limit of Unix
timestamps lets say before 1970, then you can forget about this approach as
these functions do not handle signed timestamps (-123456) ect.
So if you have
to compare birthdays for example you need another approach.
So before you start
setting up a database that accepts dates beyond the Unix margins, think twice.
ladydice (152.226.7.xxx) 29-05-2008 10:13:13

ok...i'm sori i'm really bad at this...
ok my dates are from a drop down
list...

$sdate = ("$_POST[s_year]"."-"."$_POST[
s_month]"."-"."$_POST[s_day]" ;


each element is 1 drop
down list...can i still use ur example? i'm sorry i'm new at this....
sebastien (Administrator) 29-05-2008 10:34:05

of course you can, just use :

$result = explode("-", $date); // simple case, explode is faster

$ts = mktime(0, 0, 0, $result[1], $result[2],
$result[0]);

Check www.php.net, you'll find a lot of examples!
ladydice (152.226.7.xxx) 30-05-2008 03:30:15

hmm...ok thanks for the help...
Compare dates with PHP
ladydice (152.226.7.xxx) 28-05-2008 10:51:13

what if u're not strtotime() instead u want to compare 2 different dates
from a dropdownlist. the dates from the dropdownlist are hard coded....in html
codes
Compare dates with PHP
Sebastien (84.253.21.xxx) 28-05-2008 11:01:22

You can also use the php function mktime() to create a timestamp.
See link:http://fr.php.net/manual/en/function.mktime. php to know how to use
this function.
you will probably have to parse your hard-coded date to
get all the parameters.
ladydice (152.226.7.xxx) 29-05-2008 03:52:22

Thanks...i will give it a try...been trying to solve this prob for 2 days now...

Compare dates with
ladydice (152.226.7.xxx) 29-05-2008 06:14:49

i still cant seem to get it...cld u give an example....
re: Compare dates with
sebastien (Administrator) 29-05-2008 09:14:46

ok suppose your date in your list is something like "29-08-2008
12:43"
You separate each element with your preferred substring
function (substr, explode, ...)
I'll do it with preg_split:

$date = '29-08-2008 12:43';
$result
= preg_split("/[\s\-:]/", date);
$ts =
mktime($result[3], $result[4], 0, $result[1], $result[0], $result[2]);

And
here we go, $ts contains the timestamp you want
You do the
same with your other date, so you can then compare them easily.
Write comment
Name:
Email:
 
Title:
:angry::0:confused::cheer:B):evil::silly::dry::lol::kiss::D:pinch:
:(:shock::X:side::):P:unsure::woohoo::huh::whistle:;):s
:!::?::idea::arrow:
Please input the anti-spam code that you can read in the image. If it's unreadable, please click on the image. Case insensitive.

3.23 Copyright (C) 2007 Alain Georgette / Copyright (C) 2006 Frantisek Hliva. All rights reserved."

 
Fly.net Artisan maçon