0

Possible Duplicate:
Find Month difference in php?

My server hosts multiple websites, and with some of the librarys I am using, it will be very difficult upgrading to php 5.3. I plan to do it in the near future, but not at the moment.

I have two timestamps, and I want to calculate how many months are between them. PHP 5.3 has the datetime.diff function, but since I am on 5.2, I currently can not use this.

What alternatives are there for me? I know I can just grab the seconds by subtracting the timestamps and then get the months by assuming every month has 30 days, but I will be needing an accurate result.

Your help is much appreciated.

Community
  • 1
  • 1
steeped
  • 2,613
  • 5
  • 27
  • 43

1 Answers1

1

Personally I go for this method:

$from = explode("-",date("Y-m-d",$fromStamp));
$to = explode("-",date("Y-m-d",$toStamp));
$months = ($to[0]-$from[0])*12+$to[1]-$from[1];
if( $to[1] == $from[1] && $to[2] > $from[2]) $months--; // incomplete month
if( $to[1] == ($from[1]+1)%12 && $to[2] < $from[2]) $months--; // other side
// result in $months
Niet the Dark Absol
  • 320,036
  • 81
  • 464
  • 592
  • Thank you Kolink, this works great. Very smart approach. One problem though - if today is May 16 and the date I am comparing is June 1, it would count as a full month. I will need to to count as a full month only when it is June 16. – steeped May 16 '12 at 20:39
  • 1
    @MikeGraf That's what the `($to[0]-$from[0])*12` is - years times 12. As for you, steeped, I'll add another line that'll fix that. See edit. – Niet the Dark Absol May 16 '12 at 22:17