The Tricky.net

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

Also check websites we love:
Comments
Search RSS
Old Dare compare
somnath Shinde (220.225.66.xxx) 18-07-2012 11:50:30

Hello every one i have one problem related to compare most value to current
values.

in most old value having the 01/06/1805 and compare to 17/07/2012

i
try to use strtotime()

mktime()

DateTime()

and most all but not get any
solution for that

plz help me related to that.

Thanks.
Somnath Shinde
Sander (SAdministrator) 22-07-2012 14:57:11

This is a known limitation of the way dates are handled in PHP: only dates after
1901 (and before 203 are valid (and depending on the version this range is
even smaller). Try using the DateTime class for these sort of
problems:

$datetime1 = new DateTime('1805-06-01');
$datetime2 = new
DateTime('2012-07-17');
$interval = $datetime1->diff($datetime2);
echo
$interval->format('%R%a days');
comparing dates
vikas (110.34.0.xxx) 27-06-2012 13:33:54

$exp_date = "2006-01-16";
$todays_date = date("Y-m-d";

$today
= strtotime($todays_date);
$expiration_date = strtotime($exp_date);

if
($expiration_date > $today) {
$valid = "yes";
} else {
$valid
= "no";
}
Thanks
Pratik (175.100.171.xxx) 20-03-2012 06:29:24

Thanks.....
Prof.
JP (89.100.96.xxx) 10-02-2012 01:18:43

Awesometastic!
WOW
BOB (93.217.235.xxx) 26-01-2012 18:09:51

THIS IS AWESOME
strtotime
ankit (182.64.126.xxx) 21-01-2012 09:51:21

thanx
strtotime
ankit (182.64.126.xxx) 21-01-2012 09:50:10

thanx
analpresle1989
Saul (81.25.45.xxx) 12-12-2011 12:51:01

howdy im from germany and my english isnt that fabulous, but i was able to fully
understand every  sentence of your report. Im looking english webpages
to strengthen my english capabilities and im truly happy to finally discover a
journal, that publishes clear and structured english i can have an understanding
of. Thank you from Germany! 03)
......
Collin (81.25.45.xxx) 14-07-2011 16:44:46

The very heart of your writing while sounding agreeable at first, did not settle
properly with me personally after some time. Somewhere within the paragraphs you
managed to make me a believer unfortunately only for a while. I still have a
problem with your jumps in assumptions and one would do nicely to fill in those
breaks. When you can accomplish that, I could definitely end up being amazed.
=-=
change font color based on date comparison
HansT (217.123.50.xxx) 07-06-2011 11:19:09

I have a website in which I announce events to visit.
When the date of that
event has passed, I want the font color to change from black to grey.
Anyone
with a solution? Thanks!
Sander (SAdministrator) 07-06-2011 14:08:53

The following code will output "black" if the event time is in the
future and "grey" if the event is passed (this should be a single
line):

echo $eventTime>time() ? "black" : "grey";
Anonymous (122.174.10.xxx) 11-06-2011 13:30:27

thanks
Anonymous (122.174.25.xxx) 25-05-2011 09:49:23

i need to change password of an user in records.for that i am selecting rows by
using the following and able to perform operations. But not able to get for all
the records
mysql_result($result,0), if i use like this it changes only first
record. mysql_result($result,1), this goes
to second.
i want all records to
change , what i need to change in
this?
Thanks
in advance
Anonymous (122.174.25.xxx) 25-05-2011 08:53:25

i need to change password of an user in records.
mysql_result($result,0), if
i
use like this it changes only first record. mysql_result($result,1), this
goes
to second.
i want all records to change , what i need to change in
this?
Thanks
in advance
Anonymous (122.174.25.xxx) 25-05-2011 08:52:49

i need to change password of an user in records.
mysql_resulit($result,0), if i
use like this it changes only first record. mysql_resulit($result,1), this goes
to second.
i want all records to change , what i need to change in this?
Thanks
in advance
Anonymous (122.164.177.xxx) 20-05-2011 13:52:47

i need to upload an image and a file of an user to mysql. I am able to upload
image in jpg/gif etc.,
but how to upload both at a time?

Can anybody help
me?
Thankyou
Anonymous (122.164.179.xxx) 11-05-2011 12:45:09

Moved to the correct article link:http://www.thetricky.net/php/log-in-script
Anonymous (122.164.166.xxx) 02-05-2011 13:04:51

i need to upload an image as an attachment in a php mail form.

How can do
it?

Can anybody help me plese?
Sander (SAdministrator) 02-05-2011 20:27:38

This isn't really on-topic with the article. You could ask the question on the
forum though.
ss (122.164.28.xxx) 11-04-2011 12:49:40

i need to store the login time when i logged into the application as wel
logout
time in php mysql.

How could i do it?
plz tel me if anybody
knows,plz

Thankyou
Sander (SAdministrator) 11-04-2011 19:55:30

You could add a mysql query and insert the date constructed with the strtotime
function (for more information, see the mysql date article).
ss (122.164.136.xxx) 14-04-2011 13:27:42

got it
thankyou
ss (122.164.157.xxx) 18-04-2011 10:28:44

i got it sir, thankyou

but wen i update with the same userid its not getting
updated instead it is showing empty field?
may i know why for it is?
Sander (SAdministrator) 18-04-2011 19:25:35

This depends on how your software is designed, it might be a programming error
or something else. If you want to ask more, please go to the forum.
suji (122.164.28.xxx) 11-04-2011 09:15:36

i have a leave application form with 2 date selectors.
i need number of days
after selecting both dates
how can i do this and auto fil the "number of
days" field?

plz giv me rply
thankyou
Sander (SAdministrator) 11-04-2011 20:01:00

This should be handled on the client-side, which means you have to use
javascript. First of all, get the values from the date selector, and, if needed,
convert them to date objects. Then you can use the following code to find the
number of days:

days = Math.floor((date2.getTime()-date1.getTime())/1000/
60/60/24);

(note: you can also use Math.ceil if you want to count the number of
started days instead of the number of full days)
suji (122.164.136.xxx) 14-04-2011 06:47:58

it is showing the following error

Fatal error: Call to undefined function
gettime() in C:\xampp\htdocs\xampp\sravanthi
2;php\sample-pjt\apply_leave.php on line 35
Sander (SAdministrator) 16-04-2011 13:46:34

This code was for javascript, a client-side scripting language. If you want to
implement the same thing in PHP, simply use:

$days =
floor(($dateEnd-$dateStart)/60/60/24);

Again, use ceil if you want to know the
number of started days.
suji (122.164.28.xxx) 07-04-2011 11:38:46

Character problem. empty comment
suji (122.164.28.xxx) 07-04-2011 13:14:04

i got it.
no thanks
suji (122.164.28.xxx) 07-04-2011 11:37:36

i m very new to php, i need to create login page and logout with session
storage. i tried the following:



but it shows errorCan anybody help me plz,
thankYou
Anonymous (122.166.163.xxx) 12-12-2011 09:38:52

date comparison
ss (122.164.160.xxx) 04-04-2011 13:53:11

I am using datepickers for selecting the date.I want to show an error message
when second date is greater than first one.

how can i do this? plz help
Sander (SAdministrator) 04-04-2011 14:37:42

If you want the error to appear immediately, you'll need to use javascript,
which is out of the scope of this tutorial.

If this check needs to be
server-side (in PHP), start by parsing the date (either using mktime or with
strtotime, depending on your datepicker). If the second date is bigger (just use
the ">" operator), then the second date is also later (see the third
example in strtotime).
ss (122.164.28.xxx) 06-04-2011 07:38:13

i got it in javascript, thanks
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
Adrian (188.220.57.xxx) 07-06-2011 16:39:56

I returned here because I was notified that a new comment had been posted.

I
could`nt help but notice somebody thumbed down my thank you msg (and others) to
the author for taking the time to write the information!

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.
Only registered users can write comments!

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