views:

273

answers:

7

How to get duration in terms of minutes by subtracting a previous time stamp from the present time in PHP?

The format of time stamp is like

2009-12-05 10:35:28

I want to calculate how many minutes have passed. How to do it?

A: 

Check out some pretty date libraries in PHP. Might have something for you. Here's one : http://www.zachleat.com/web/2008/02/10/php-pretty-date/

Ritesh M Nayak
A: 
strtotime("now") - strtotime("2009-12-05 10:35:28")

That will get you seconds difference. Divide by 60 for minutes elapsed. If you have any information on the time zone of the initial timestamp, however, you'd need to adjust the "now" to a more comparable time

Alex Mcp
You could use time() instead of strtotime("now")
echo
A: 

something like that

$second = strtotime('now') - strtotime($your_date);
$minute = $second / 60;

strtotime return the number of seconds since January 1 1970 00:00:00 UTC, so you can easily manipulate this. if you need don't want to have 35.5 minute you can use floor to round up the number. Last remark both time need to be in the same timezone or you are going to count the timezone difference also.

RageZ
A: 

You could just use

$timestamp = time();

$diff = time() - $timestamp

$minutes = date( i, $diff );

Balls-of-steel
that definitely won't work. think about it, it will return something like 01:11:20 and you're getting the 11 part only.
thephpdeveloper
It is not what I want.
Steven
A: 

If you don't wanna add a library, you can do this pretty easily:

<?php 
$date1 = "2009-12-05 10:35:28";
$date2 = "2009-12-07 11:58:12";
$diff = strtotime($date2) - strtotime($date1);
$minutes_passed = $diff/60;
echo $minutes_passed." minutes have passed between ".$date1." and ".$date2; 
?>
Bill Huertas
How to do it in MySQL instead of PHP?
Steven
A: 
function timeAgoMin($timestamp){
  if(!is_int($timestamp)){
    $timestamp = strtotime($timestamp);
  }

  return ((time() - $timestamp) / 60);

}
thephpdeveloper
How to do it in MySQL? There is a column/field that stores a previous time stamp.
Steven
extract the timestamp and parse it through this function?
thephpdeveloper
+1  A: 

To do this in MySQL use the TIMESTAMPDIFF function:

SELECT TIMESTAMPDIFF(MINUTE, date_lastaccess, NOW()) FROM session;

Where session is the table and date_lastaccess is a DATE / DATETIME field.

pygorex1