1

Possible Duplicate:
How to find number of days between two dates using php

I'm trying to compare two dates that are stored in two PHP variables. $curDate and $prevDate are stored in the format yyyy-mm-dd. To simply display them, I've been using date("n,j,Y", strtotime($prevDate)) or some other combination of the first parameters of the date function.

I want to compare the $curDate and $prevDate on the scale of days, but the trouble is, the 31st could be 1 day from the 1st so if I just look at the date in this way then I can't handle that behavior.

I've looked into the PHP Function JulianToJD() but can't just pass the SQL date, formatted thru the date() and strtotime() function.

Can someone help me figure out a clever way of comparing two dates on the scale of days while paying attention to the end of months?

2
  • 1
    See stackoverflow.com/q/2040560/469210 Commented Jul 5, 2011 at 15:06
  • @borrible This worked. Add this as an answer and I'll accept it. Commented Jul 5, 2011 at 15:35

2 Answers 2

3

See stackoverflow.com/q/2040560/469210. I.e. calculate the diff of the dates and apply the floor function:

floor($datediff/(60*60*24));
Sign up to request clarification or add additional context in comments.

Comments

3

You could do it two ways:

MySQL:

SELECT (TO_DAYS(curDate) - TO_DAYS(prevDate)) as Days ...

which gives you the difference in days (TO_DAYS() returns the number of days since year 0)

PHP, using DateTime:

$prev = DateTime::CreateFromFormat('Y-m-d', $prevDate);
$cur = DateTime::CreateFromFormat('Y-m-d', $curDate);

$days = $cur->diff($prev)->format('%a');

12 Comments

this looks good, however, I get an error on the first line of PHP, $prev=....: `Parse error: syntax error, unexpected T_STRING, expecting T_VARIABLE or '$'
Woops, sorry. take out the "new" portion. I'll edit the answer.
+1 I don't like the MySQL way; the PHP way is nice and clean!
@Marc Taking out the new did fix that error, but I don't think this works as it should. I printed out $prevDate and $curDate which are 2011-03-12 and 2011-07-04, respectively. The output for days is 6015???
@Marc as a side note, those date outputs by nature might seem ambiguous with the month/day, but they are in the Y-m-d format.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.