Jump to content

Calculate time elapsed


cordoprod

Recommended Posts

Hello.

 

I want to calculate how many seconds,hours,days,months,years elapsed since a timestamp created from time();

 

Let's say i have a timestamp from now, and in 30 minutes it shows 30 minutes and when it has gone one and a half hour it says 1 hour and 30 minutes..

 

Do you know how to do this?

Link to comment
https://forums.phpfreaks.com/topic/103845-calculate-time-elapsed/
Share on other sites

A function of mine:

 

<?php
// This function returns an array('years' => $years, 'months' => $months, 'days' => $days, 'hours' => $hours, 'minutes' => $minutes, 'seconds' => $seconds)
// If parameters contain only digits, they are treated as Unix timestamps, else they are converted using strtotime()
// If no $endTime is provided, the function uses the current time
// Fails on timestamps prior to ~ 1970 due to Unix timestamp limitations on PHP versions prior to 5.1.0
function timeDifference($startTime, $endTime = false) {
$startTime = ctype_digit($startTime) ? $startTime : strtotime($startTime);
$endTime = $endTime ? (ctype_digit($endTime) ? $endTime : strtotime($endTime)) : time();

if ($endTime > $startTime) {
	$diff = $endTime - $startTime;
	return array('years' => gmdate('Y', $diff) - 1970, 'months' => gmdate('m', $diff) - 1, 'days' => gmdate('d', $diff) - 1, 'hours' => gmdate('H', $diff), 'minutes' => gmdate('i', $diff), 'seconds' => gmdate('s', $diff));
} else {
	die('endTime parameter must be larger than startTime parameter in timeDifference function.');
}
}
// Sample usage
$array = timeDifference('2008-05-02 10:30:00');
foreach($array as $unit => $value) {
echo $value, ' ', (($value == 1) ? substr($unit, 0, -1) : $unit), '<br />';
}
?>

 

And this foreach will probably fit your goal better:

 

<?php
foreach($array as $unit => $value) {
if ($value == 0) continue;
if ($unit == 'seconds') continue;
echo ltrim($value, '0'), ' ', (($value == 1) ? substr($unit, 0, -1) : $unit), ' ';
}
?>

As read from the comments:

 

<?php

// This function returns an array('years' => $years, 'months' => $months, 'days' => $days, 'hours' => $hours, 'minutes' => $minutes, 'seconds' => $seconds)

// If parameters contain only digits, they are treated as Unix timestamps, else they are converted using strtotime()<--

// If no $endTime is provided, the function uses the current time

// Fails on timestamps prior to ~ 1970 due to Unix timestamp limitations on PHP versions prior to 5.1.0

function timeDifference($startTime, $endTime = false) {

$startTime = ctype_digit($startTime) ? $startTime : strtotime($startTime);

$endTime = $endTime ? (ctype_digit($endTime) ? $endTime : strtotime($endTime)) : time();

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.