Jump to content

[SOLVED] Date Subraction


timmah1

Recommended Posts

I need to subtract two dates.

 

What's the easiest way of doing this?

 

I have this

$b = date("M j, Y H:i:s",$row6['date']) - date("M j, Y H:i:s",$row6['duration']);

Then display as this

echo date("M j, Y H:i:s",$b)

 

But it keeps showing up as Dec 31, 1969 18:00:00.

 

$row6['date']

$row6['dauration']

both fields are datetime (0000-00-00 00:00:00)

 

Thanks in advance.

Link to comment
https://forums.phpfreaks.com/topic/88526-solved-date-subraction/
Share on other sites

Try out this function OR can get more idea from http://my.php.net/datetime.if u want to use php.

 

<?php
Function DateDiff($date1,$date2) {
  $timedifference=$date2-$date1;
  $corr=date("I",$date2)-date("I",$date1);
  $timedifference+=$corr;
  return $timedifference;
}


$d1=mktime(2,0,0,10,28,2007);
$d2=mktime(4,0,0,10,29,2007);
$period=DateDiff($d1,$d2);
printf("<br>%s",date("I d.m.Y H:i",$d1));
printf("<br>%u hour",$period/3600);
printf("<br>%s",date("I d.m.Y H:i",$d2));
?>

 

To use mysql:

http://dev.mysql.com/doc/refman/5.0/en/date-and-time-functions.html

So right now, my select statement is this:

$today = date("Y-m-d H:i:s");
$items= "SELECT * FROM items WHERE duration >= '$today'";

 

How would I implement what you said?

 

 

<?php
$today = date("Y-m-d H:i:s");
$items= "SELECT DATEDIFF(date1,date2) FROM items WHERE duration >= '$today'";
?>

I used one of these examples, but nothing is displaying

 

$date1 = date("Y-m-d H:i:s");
$date2 = $myrow2['duration'];

function DateDiff($date1,$date2) {
  $timedifference=$date2-$date1;
  $corr=date("I",$date2)-date("I",$date1);
  $timedifference+=$corr;
  return $timedifference;
}

ok, I got it to work, but call me dumb, but how do I get this to display like this

 

23 hours, 17 minutes?

 

Right now it displays like this:

Array ( [23] => hours [17] => minutes )

 

Here's the code

function date_diff($d1, $d2){
    $d1 = (is_string($d1) ? strtotime($d1) : $d1);
    $d2 = (is_string($d2) ? strtotime($d2) : $d2);

    $diff_secs = abs($d1 - $d2);
    $base_year = min(date("Y", $d1), date("Y", $d2));

    $diff = mktime(0, 0, $diff_secs, 1, 1, $base_year);
    return array(
          date("H", $diff) => "hours",
         (int) date("i", $diff) => "minutes",
    );
}

$a = date_diff("$d1", "$d2");

print_r($a);

 

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.