1

I need a function in php4 that will calculate the date difference in the provided date format. eg.

$date1 = "2011-08-24 10:03:00";
$date2 = "2012-09-24 10:04:31";
$format1 = "Y W" ; //This format should return the difference in Year and week.
$format2 = "M D"; // This format should return the difference in Months and days.
// The format can be any combination of Year,Month,Day,Week,Hour,Minute,Second.

function ConvertDate($data1,$date2,$format) 

Please let me know if you need any more details on this. Thanks in advance.

sagar27
  • 3,121
  • 3
  • 27
  • 37
  • 3
    As if I really need to say this, but you really **need** to upgrade your PHP version first. PHP4 hasn't been supported for quite some time... – ircmaxell Jan 22 '11 at 20:46
  • yes actually i agree with you that in php5 there are good functions for this thing , but i need to do this in php4 only as i have to give support for php4 also. – sagar27 Jan 23 '11 at 05:44

2 Answers2

3

Get Unix timestamps of your dates using mktime. Then you get the difference for:

$years = floor(($date2-$date1)/31536000);
$months = floor(($date2-$date1)/2628000);
$days = floor(($date2-$date1)/86400);
$hours = floor(($date2-$date1)/3600);
$minutes = floor(($date2-$date1)/60);
$seconds = ($date2-$date1);

Hope this helps.
—Alberto

Donovan
  • 6,002
  • 5
  • 41
  • 55
3

Let's try something like this.

function ConvertDate($date1, $date2, $format)
{
    static $formatDefinitions = array(
        'Y' => 31536000,
        'M' => 2592000,
        'W' => 604800,
        'D' => 86400,
        'H' => 3600,
        'i' => 60,
        's' => 1
    );

    $ts1 = strtotime($date1);
    $ts2 = strtotime($date2);
    $delta = abs($ts1 - $ts2);

    $seconds = array();
    foreach ($formatDefinitions as $definition => $divider) {
        if (false !== strpos($format, $definition)) {
            $seconds[$definition] = floor($delta / $divider);
            $delta = $delta % $divider;
        }
    }

    return strtr($format, $seconds);
}

Just keep in mind that months and years are just estimated because you cannot say "how many seconds are a month" (because a "month" can be anything between 28 and 31 days). My function counts a month as 30 days.

Andrewsville
  • 106
  • 2
  • btw I'm not quite sure if there are static variables in PHP4. If not, just delete the static keyword :) – Andrewsville Jan 22 '11 at 21:06
  • PHP says «For compatibility with PHP 4, if no visibility declaration is used, then the property or method will be treated as if it was declared as public.» – Donovan Jan 22 '11 at 23:05
  • Thanks for you reply.The code is working nice and fine for all the test cases. – sagar27 Jan 24 '11 at 04:58