Format seconds (if less or equal to 86400) into hours, minutes and seconds ± 1 sec. Change $time and $myLocale to whatever your want and test from CLI (bash - linux) with
t=''; for i in $(seq 1 20); do t=$t"\n"$(php -f seconds2time.php) ; done ; echo -e "$t" | sort -n
<?php
$time = mt_rand(0,86400);
$myLocale = "es_AR";
setlocale(LC_ALL,$myLocale);
$localeconv = localeconv();
$dec_point =$localeconv['decimal_point'];
($time > 86400) ? die("Time must be less than 86400 seconds") : '';
if($time % 3600 == 0){
$t_h[0] = $time/3600;
$t_m[0] = 0;
$t_s[0] = 0;
}else if ($time >= 3600 && ($time % 60) == 0 ){
$t_h = explode($dec_point,$time / 3600);
$t_m = explode($dec_point,('0.'.$t_h[1]) * 3600 / 60);
$t_s[0] = 0;
}else if($time < 3600 && ($time % 60) == 0 ){
$t_h[0] = 0;
$t_m = explode($dec_point,$time/ 60);
$t_s[0] = 0;
}else{
$t_h = explode($dec_point,$time / 3600);
$t_m = explode($dec_point,('0.'.$t_h[1]) * 3600 / 60);
$t_s[0] = ceil(('0.'.$t_m[1]) * 60);
}
print sprintf('%05d',$time) .' = ' . sprintf('%02d',$t_h[0]). ' hs. '. sprintf('%02d',$t_m[0]) . ' min. ' .sprintf('%02d',$t_s[0]) ." seg. \n";
?>
time
(PHP 4, PHP 5)
time — Zwraca aktualny uniksowy znacznik czasu
Opis
int time
( void
)
Zwraca aktualny czas, podawany jako liczba sekund, które upłynęły od uniksowej Epoki (1 stycznia 1970 00:00:00 GMT).
Przykłady
Example #1 time() przykład
<?php
$nextWeek = time() + (7 * 24 * 60 * 60);
// 7 dni; 24 godziny; 60 minut; 60 sekund
echo 'Teraz: '. date('Y-m-d') ."\n";
echo 'Za tydzień: '. date('Y-m-d', $nextWeek) ."\n";
// lub używając strtotime():
echo 'Za tydzień: '. date('Y-m-d', strtotime('+1 week')) ."\n";
?>
Powyższy przykład wyświetli coś podobnego do:
Teraz: 2005-03-30 Za tydzień: 2005-04-06 Za tydzień: 2005-04-06
Notatki
Wskazówka
Znacznik czasu od rozpoczęcia żądania jest dostępny w $_SERVER['REQUEST_TIME'] od PHP 5.1.
time
south dot minds at gmail dot com
16-May-2008 05:09
16-May-2008 05:09
binupillai2003 at yahoo dot com
03-Apr-2008 07:10
03-Apr-2008 07:10
Calculate time difference(24 hours system)
<?php
//Author Binu.v.Pillai
function diffTime($bigTime,$smallTime)
{
//input format hh:mm:ss
list($h1,$m1,$s1)=split(":",$bigTime);
list($h2,$m2,$s2)=split(":",$smallTime);
$second1=$s1+($h1*3600)+($m1*60);//converting it into seconds
$second2=$s2+($h2*3600)+($m2*60);
if ($second1==$second2)
{
$resultTime="00:00:00";
return $resultTime;
exit();
}
if ($second1<$second2) //
{
$second1=$second1+(24*60*60);//adding 24 hours to it.
}
$second3=$second1-$second2;
//print $second3;
if ($second3==0)
{
$h3=0;
}
else
{
$h3=floor($second3/3600);//find total hours
}
$remSecond=$second3-($h3*3600);//get remaining seconds
if ($remSecond==0)
{
$m3=0;
}
else
{
$m3=floor($remSecond/60);// for finding remaining minutes
}
$s3=$remSecond-(60*$m3);
if($h3==0)//formating result.
{
$h3="00";
}
if($m3==0)
{
$m3="00";
}
if($s3==0)
{
$s3="00";
}
$resultTime="$h3:$m3:$s3";
return $resultTime;
}
?>
Rana Email: rana_0036 at yahoo dot com
17-Mar-2008 07:03
17-Mar-2008 07:03
Here some example i have implemented. I think it will be helpful someone.
function fullDateFormat( $value ){
$d = explode("-", $value);
$cdate = date ("F j, Y", mktime (0,0,0,$d[1],$d[2],$d[0]));
echo $cdate;
}
//-----Enter date format like mysql date (e.g. 2000-01-30)------//
fullDateFormat("2008-03-17");
function detailsDateFormat( $value ){
$d = explode("-", $value);
$cdate = date ("l F j, Y", mktime (0,0,0,$d[1],$d[2],$d[0]));
echo $cdate;
}
//-----Enter date format like mysql date (e.g. 2000-01-30)------//
detailsDateFormat("2008-03-17");
Anonymous
11-Feb-2008 03:37
11-Feb-2008 03:37
Hi Tom Guilleaume,
I hope your way to convert from timestamp to readable date didn't take as long as it looks like it did...
Firstly, it gives incorrect dates.
echo reverse_unix_timestamp(1201212000,long);
gives "January 23 2008 10:: pm" (should be Jan 24th).
Secondly, you can replace the whole of your function with the ready to use PHP 'date' function like this:
echo date('F d Y h:i:s A',1201212000); // January 24 2008 10:00:00 PM
Tom Guilleaume
05-Feb-2008 02:46
05-Feb-2008 02:46
Here is a very unpolished way to reverse the unix stamp and turn it into a readable date
function reverse_unix_timestamp($timestamp,$long_or_short){
$fouryears = '126230400';
$year = '31536000';
$leapyear = '31622400';
$day = '86400';
$hour = '3600';
$minute = '60';
$second = '1';
//9 "four years" for 2008
$yearnow = 1970;
$timeleft = $timestamp;
while ($timeleft >= $fouryears){
$timeleft = $timeleft - $fouryears;
$yearnow = $yearnow + 4;
}
//now see if its a leapyear
$lycheck = $yearnow / 4;
$lycheckr = round($yearnow / 4,0);
//if they are the same, it is a leap year and we have to add the extra day
while ($timeleft >= $leapyear){
if ($lycheck == $lycheckr){
$yearnow++;
$timeleft = $timeleft - $leapyear;
$leapyearnow = 'yes';
}else{
$yearnow++;
$timeleft = $timeleft - $year;
$leapyearnow = 'no';
}
}
//make sure there isnt enough left for just one year, and also make sure its not negative time left.
if (($timeleft > $year) && ($timeleft < $leapyear)){
$yearnow++;
$timeleft = $timeleft - $year;
}
if ($timeleft < 0){
$date = 'Error';
}
$daynow = 0;
while ($timeleft >= $day){
$timeleft = $timeleft - $day;
$daynow++;
}
while ($timeleft >= $hour){
$timeleft = $timeleft - $hour;
$hournow++;
}
if ($hournow > 12){
$add = 'pm';
$hournow = $hournow - 12;
}else{
$add = 'am';
}
while ($timeleft >= $minute){
$timeleft = $timeleft - $minute;
$minutenow++;
}
while ($timeleft >= $second){
$timeleft = $timeleft - $second;
$secondnow++;
}
if ($timeleft != 0){
$date = 'Error2';
}
if ($leapyearnow == 'yes'){
$aod = 1;
}
if ($daynow <= 31){
$month0 = 'January';
$month1 = '1';
}elseif ($daynow <= 59 + $aod){
$month0 = 'February';
$month1 = '2';
$daynow = $daynow - 31;
}elseif ($daynow <= 90 + $aod){
$month0 = 'March';
$month1 = '3';
$daynow = $daynow - 59 + $aod;
}elseif ($daynow <= 120 + $aod){
$month0 = 'April';
$month1 = '4';
$daynow = $daynow - 90 + $aod;
}elseif ($daynow <= 151 + $aod){
$month0 = 'May';
$month1 = '5';
$daynow = $daynow - 120 + $aod;
}elseif ($daynow <= 181 + $aod){
$month0 = 'June';
$month1 = '6';
$daynow = $daynow - 151 + $aod;
}elseif ($daynow <= 212 + $aod){
$month0 = 'July';
$month1 = '7';
$daynow = $daynow - 181 + $aod;
}elseif ($daynow <= 243 + $aod){
$month0 = 'August';
$month1 = '8';
$daynow = $daynow - 212 + $aod;
}elseif ($daynow <= 273 + $aod){
$month0 = 'September';
$month1 = '9';
$daynow = $daynow - 243 + $aod;
}elseif ($daynow <= 304 + $aod){
$month0 = 'October';
$month1 = '10';
$daynow = $daynow - 273 + $aod;
}elseif ($daynow <= 334 + $aod){
$month0 = 'November';
$month1 = '11';
$daynow = $daynow - 304 + $aod;
}elseif ($daynow <= 365 + $aod){
$month0 = 'December';
$month1 = '12';
$daynow = $daynow - 334 + $aod;
}
$date1 = $month1.'.'.$daynow.'.'.$yearnow.' '.$hournow.':'.$minutenow.':'.$secondnow.' '.$add;
$date0 = $month0.' '.$daynow.' '.$yearnow.' '.$hournow.':'.$minutenow.':'.$secondnow.' '.$add;
if ($long_or_short != 'long'){
return $date1;
}else{
return $date0;
}
}
to be used without permission for personal use
miguelangeldavila at yahoo dot com dot mx
24-Dec-2007 06:50
24-Dec-2007 06:50
PHP is affected by the Y2K38 bug.
<?php
$current_time = time();
$years_from_now = 50;
$remaining_seconds = 60 * 60 * 24 * 365 * $years_from_now;
$future_unix_time = $current_time + $remaining_seconds;
$future_date = date('Y-m-d', $future_unix_time);
echo $future_date;
// 1921-11-05
?>
It is caused because the PHP uses the C 32 bits time function
stack-phpnotes at landstander dot com
23-Oct-2007 01:31
23-Oct-2007 01:31
My modification and enhancements to the timeDiff() function last updated by sean sullivan. The rewrite was done to add a couple new optional parameters but I also got a bump in performance. On a completely personal preference level I changed the month and year second values with ones I got from Google searches.
Written and tested with 5.2.0.
Options include
to = time(); date to compute the range to
parts = 1; number of parts to display max
precision = 'second'; lowest part to compute to
distance = TRUE; include the 'ago' or 'away' bit
separator = ', '; separates the parts
<?php
function timeDiff($time, $opt = array()) {
// The default values
$defOptions = array(
'to' => 0,
'parts' => 1,
'precision' => 'second',
'distance' => TRUE,
'separator' => ', '
);
$opt = array_merge($defOptions, $opt);
// Default to current time if no to point is given
(!$opt['to']) && ($opt['to'] = time());
// Init an empty string
$str = '';
// To or From computation
$diff = ($opt['to'] > $time) ? $opt['to']-$time : $time-$opt['to'];
// An array of label => periods of seconds;
$periods = array(
'decade' => 315569260,
'year' => 31556926,
'month' => 2629744,
'week' => 604800,
'day' => 86400,
'hour' => 3600,
'minute' => 60,
'second' => 1
);
// Round to precision
if ($opt['precision'] != 'second')
$diff = round(($diff/$periods[$opt['precision']])) * $periods[$opt['precision']];
// Report the value is 'less than 1 ' precision period away
(0 == $diff) && ($str = 'less than 1 '.$opt['precision']);
// Loop over each period
foreach ($periods as $label => $value) {
// Stitch together the time difference string
(($x=floor($diff/$value))&&$opt['parts']--) && $str.=($str?$opt['separator']:'').($x.' '.$label.($x>1?'s':''));
// Stop processing if no more parts are going to be reported.
if ($opt['parts'] == 0 || $label == $opt['precision']) break;
// Get ready for the next pass
$diff -= $x*$value;
}
$opt['distance'] && $str.=($str&&$opt['to']>$time)?' ago':' away';
return $str;
}
?>
Usage:
$span = timeDiff($when);
or
$span = timeDiff($when, array('parts' => 3));
Josh Abraham
28-Sep-2007 04:43
28-Sep-2007 04:43
When dealing with the results of the time function, taking the modulus (remainder) is often a good way to find recurring information such as day of the week, week of the year, or month of the year. In the example given below of a firefighter's shift, you could do the following to simplify the code.
<?php
function whatShift() {
$referencePoint = mktime(7, 0, 0, 9, 11, 2004); // Sept 11, 2004 at 7AM started an A Shift.
//This is the where we divide the current time since reference by the amount of time in all shifts
//The result of this is the remainder.
$sinceReference = (time() - $referencePoint) % (60 * 60 * 24 * 3);
//The rest of the code can be basically the same so I shortened it here.
if ($sinceReference < 60 * 60 * 25) $shift = "A";
elseif ($sinceReference < 60 * 60 * 49) $shift = "B";
else $shift = "C";
return $shift;
}
?>
jon at freilich dot com
21-Sep-2007 06:30
21-Sep-2007 06:30
Fire Fighters typically work one day on and two days off. Known as shifts and generally referred to as A, B and C. I need to compute this for a web script so I came up with the following function.
Notes: You may need to change the reference date as not all departments are on the same rotation. Also, this does not take into account daylight savings time so the changeover moves by an hour.
<?php
function whatShift() {
$referencePoint = mktime(7, 0, 0, 9, 11, 2004); // Sept 11, 2004 at 7AM started an A Shift.
$now = time();
// Next we need to know how many seconds since the start of the last A Shift.
// First we compute how many 3 days cycles since the reference point then
// subtract that number.
$difference = ($now - $referencePoint);
$cycles = floor($difference / (60 * 60 * 24 * 3));
$sinceReference = ($difference - ($cycles * 60 * 60 * 24 * 3));
if ($sinceReference < 60 * 60 * 25) { // Before the start of the 25th hour it's A Shift.
$shift = "A";
}
elseif ($sinceReference < 60 * 60 * 49) { // Else before the start of the 49th hour it's B Shift.
$shift = "B";
}
else {
$shift = "C"; // Else it's C Shift.
}
return $shift;
}
?>
kobieta dot ryba at gmail dot com
12-Sep-2007 01:23
12-Sep-2007 01:23
Time left function:
<?php
define("TIME_PERIODS_PLURAL_SINGULAR", "weeks:week,years:year,days:day,hours:hour, : ,minutes:minute,seconds:second");
DEFINE("TIME_LEFT_STRING_TPL", " #num# #period#");
/**
* @param $time time stamp
**/
function time_left($time)
{
if (($now = time()) <= $time) return false;
$timeRanges = array('years' => 365*60*60*24,/* 'weeks' => 60*60*24*7, */ 'days' => 60*60*24, 'hours' => 60*60, 'minutes' => 60, 'seconds' => 1);
$secondsLeft = $now-$time;
// prepare ranges
$outRanges = array();
foreach ($timeRanges as $period => $sec)
if ($secondsLeft/$sec >= 1)
{
$outRanges[$period] = floor($secondsLeft/$sec);
$secondsLeft -= ($outRanges[$period] * $sec);
}
// playing with TIME_PERIODS_PLURAL_SINGULAR
$periodsEx = explode(",", TIME_PERIODS_PLURAL_SINGULAR);
$periodsAr = array();
foreach ($periodsEx as $periods)
{
$ex = explode(":", $periods);
$periodsAr[$ex[0]] = array('plural' => $ex[0], 'singular' => $ex[1]);
}
// string out
$outString = "";
$outStringAr = array();
foreach ($outRanges as $period => $num)
{
$per = $periodsAr[$period]['plural'];
if ($num == 1) $per = $periodsAr[$period]['singular'];
$outString .= $outStringAr[$period] = str_replace(array("#num#", "#period#"), array($num, $per), TIME_LEFT_STRING_TPL);
}
return array('timeRanges' => $outRanges, 'leftStringAr' => $outStringAr, 'leftString' => $outString);
}
print_r(time_left(time()-60*60*24*365+59));
?>
Output:
Array
(
[timeRanges] => Array
(
[days] => 364
[hours] => 23
[minutes] => 59
[seconds] => 1
)
[leftStringAr] => Array
(
[days] => 364 days
[hours] => 23 hours
[minutes] => 59 minutes
[seconds] => 1 second
)
[leftString] => 364 days 23 hours 59 minutes 1 second
)
by225 at yahoo dot com
06-Sep-2007 09:32
06-Sep-2007 09:32
A function for converting to Unix time without using the MySQL UNIX_TIMESTAMP function in a query (MySQL allows eight different formats for timestamps):
function UnixTime($mysql_timestamp){
if (preg_match('/(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})/', $mysql_timestamp, $pieces)
|| preg_match('/(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})/', $mysql_timestamp, $pieces)) {
$unix_time = mktime($pieces[4], $pieces[5], $pieces[6], $pieces[2], $pieces[3], $pieces[1]);
} elseif (preg_match('/\d{4}\-\d{2}\-\d{2} \d{2}:\d{2}:\d{2}/', $mysql_timestamp)
|| preg_match('/\d{2}\-\d{2}\-\d{2} \d{2}:\d{2}:\d{2}/', $mysql_timestamp)
|| preg_match('/\d{4}\-\d{2}\-\d{2}/', $mysql_timestamp)
|| preg_match('/\d{2}\-\d{2}\-\d{2}/', $mysql_timestamp)) {
$unix_time = strtotime($mysql_timestamp);
} elseif (preg_match('/(\d{4})(\d{2})(\d{2})/', $mysql_timestamp, $pieces)
|| preg_match('/(\d{2})(\d{2})(\d{2})/', $mysql_timestamp, $pieces)) {
$unix_time = mktime(0, 0, 0, $pieces[2], $pieces[3], $pieces[1]);
}
return $unix_time;
}
lsd25 at hotmail dot com
01-Sep-2007 04:53
01-Sep-2007 04:53
I did an article on floating point time you can download from my website. Roun movements is the radial ounion movement and there is a quantum ounion movement as well, this code will generate the data for http://www.chronolabs.org.au/bin/roun-time-article.pdf which is an article on floating point time, I have created the calendar system as well for this time. It is compatible with other time and other solar systems with different revolutions of the planets as well as different quantumy stuff.
Thanks:
<?
if ($gmt>0){
$gmt=-$gmt;
} else {
$gmt=$gmt+$gmt+$gmt;
}
$ptime = strtotime('2008-05-11 10:05 AM')+(60*60*gmt);
$weight = -20.22222222223+(1*gmt);
$roun_xa = ($tme)/(24*60*60);
$roun_ya = $ptime/(24*60*60);
$roun = (($roun_xa -$roun_ya) - $weight)+(microtime/999999);
$nonedeficient = array("seq1" => array(31,30,31,30,30,30,31,30,31,30,31,30),
"seq2" => array(31,30,31,30,31,30,31,30,31,30,31,30),
"seq3" => array(31,30,31,30,30,30,31,30,31,30,31,30),
"seq4" => array(31,30,31,30,30,30,31,30,31,30,31,30));
$deficient = array("seq1" => array(31,30,31,30,30,30,31,30,31,30,31,30),
"seq2" => array(31,30,31,30,31,30,31,30,31,30,31,30),
"seq3" => array(31,30,31,30,31,30,31,30,30,30,31,30),
"seq4" => array(30,30,31,30,31,30,31,30,31,30,31,30));
$monthusage = isset($_GET['deficienty']) ? ${$_GET['deficienty']} : $deficient;
foreach($monthusage as $key => $item){
$i++;
foreach($item as $numdays){
$ttl_num=$ttl_num+$numdays;
}
}
$revolutionsperyear = $ttl_num / $i;
$numyears = round((round(ceil($roun)) / $revolutionsperyear),0);
$jtl = abs(abs($roun) - ceil($revolutionsperyear*($numyears+1)));
while($month==0){
$day=0;
foreach($monthusage as $key => $item){
$t++;
$u=0;
foreach($item as $numdays){
if ($ii<abs($roun)){
$isbelow=true;
}
$ii=$ii+$numdays;
if ($ii>abs($roun)){
$isabove=true;
}
if ($isbelow==true&&$isabove==true){
$daynum = floor(($ii-$numday)-abs($roun));
$month = $u;
$month++;
$isbelow=false;
$isabove=false;
$nodaycount=true;
}
if ($nodaycount==false)
$day++;
$u++;
}
}
}
$timer = substr($roun, strpos($roun,'.')+1,strlen($roun)-strpos($roun,'.')-1);
$roun_out= $numyears.'-'.$month.'-'.$daynum.' '.$day.".$timer";
?>
Sean Sullivan
28-Jul-2007 09:51
28-Jul-2007 09:51
Fixed divide by zero warnings given by the timeDiff function. The change is that the for loop doesn't count down to 0 anymore, just 1. I dont think it has any side effects.
# max_detail_levels - how deep to go down? If max_detail_levels is set to 2, text will output something like "3 days 4 hours" instead of "3 days 4 hours 10 minutes 55 seconds"
# precision_level - this is what rspenc29 was trying to accomplish. If you want to only report a minimum value of say 1 hour, then you should set this to "hour"
function timeDiff($timestamp,$detailed=false, $max_detail_levels=8, $precision_level='second'){
$now = time();
#If the difference is positive "ago" - negative "away"
($timestamp >= $now) ? $action = 'away' : $action = 'ago';
# Set the periods of time
$periods = array("second", "minute", "hour", "day", "week", "month", "year", "decade");
$lengths = array(1, 60, 3600, 86400, 604800, 2630880, 31570560, 315705600);
$diff = ($action == 'away' ? $timestamp - $now : $now - $timestamp);
$prec_key = array_search($precision_level,$periods);
# round diff to the precision_level
$diff = round(($diff/$lengths[$prec_key]))*$lengths[$prec_key];
# if the diff is very small, display for ex "just seconds ago"
if ($diff <= 10) {
$periodago = max(0,$prec_key-1);
$agotxt = $periods[$periodago].'s';
return "just $agotxt $action";
}
# Go from decades backwards to seconds
$time = "";
for ($i = (sizeof($lengths) - 1); $i>0; $i--) {
if($diff > $lengths[$i-1] && ($max_detail_levels > 0)) { # if the difference is greater than the length we are checking... continue
$val = floor($diff / $lengths[$i-1]); # 65 / 60 = 1. That means one minute. 130 / 60 = 2. Two minutes.. etc
$time .= $val ." ". $periods[$i-1].($val > 1 ? 's ' : ' '); # The value, then the name associated, then add 's' if plural
$diff -= ($val * $lengths[$i-1]); # subtract the values we just used from the overall diff so we can find the rest of the information
if(!$detailed) { $i = 0; } # if detailed is turn off (default) only show the first set found, else show all information
$max_detail_levels--;
}
}
# Basic error checking.
if($time == "") {
return "Error-- Unable to calculate time.";
} else {
return $time.$action;
}
}
nimit dot maru at dontspam-gmail dot com
19-Jul-2007 10:56
19-Jul-2007 10:56
Correcting some problems with rspenc29's addition, and adding another feature:
# max_detail_levels - how deep to go down? If max_detail_levels is set to 2, text will output something like "3 days 4 hours" instead of "3 days 4 hours 10 minutes 55 seconds"
# precision_level - this is what rspenc29 was trying to accomplish. If you want to only report a minimum value of say 1 hour, then you should set this to "hour"
function timeDiff($timestamp,$detailed=false, $max_detail_levels=8, $precision_level='second'){
$now = time();
#If the difference is positive "ago" - negative "away"
($timestamp >= $now) ? $action = 'away' : $action = 'ago';
# Set the periods of time
$periods = array("second", "minute", "hour", "day", "week", "month", "year", "decade");
$lengths = array(1, 60, 3600, 86400, 604800, 2630880, 31570560, 315705600);
$diff = ($action == 'away' ? $timestamp - $now : $now - $timestamp);
$prec_key = array_search($precision_level,$periods);
# round diff to the precision_level
$diff = round(($diff/$lengths[$prec_key]))*$lengths[$prec_key];
# if the diff is very small, display for ex "just seconds ago"
if ($diff <= 10) {
$periodago = max(0,$prec_key-1);
$agotxt = $periods[$periodago].'s';
return "just $agotxt $action";
}
# Go from decades backwards to seconds
$time = "";
for ($i = (sizeof($lengths) - 1); $i>=0; $i--) {
if($diff > $lengths[$i-1] && ($max_detail_levels > 0)) { # if the difference is greater than the length we are checking... continue
$val = floor($diff / $lengths[$i-1]); # 65 / 60 = 1. That means one minute. 130 / 60 = 2. Two minutes.. etc
$time .= $val ." ". $periods[$i-1].($val > 1 ? 's ' : ' '); # The value, then the name associated, then add 's' if plural
$diff -= ($val * $lengths[$i-1]); # subtract the values we just used from the overall diff so we can find the rest of the information
if(!$detailed) { $i = 0; } # if detailed is turn off (default) only show the first set found, else show all information
$max_detail_levels--;
}
}
# Basic error checking.
if($time == "") {
return "Error-- Unable to calculate time.";
} else {
return $time.$action;
}
}
rspenc29 at gmail dot com
14-Jun-2007 03:33
14-Jun-2007 03:33
To further expand on shdowhawk's timeDiff function I added a small but important feature
function timeDiff($timestamp,$detailed=false,$n = 0){
$now = time();
#If the difference is positive "ago" - negative "away"
($timestamp >= $now) ? $action = 'away' : $action = 'ago';
$diff = ($action == 'away' ? $timestamp - $now : $now - $timestamp);
# Set the periods of time
$periods = array("second", "minute", "hour", "day", "week", "month", "year", "decade");
$lengths = array(1, 60, 3600, 86400, 604800, 2630880, 31570560, 315705600);
# Go from decades backwards to seconds
$i = sizeof($lengths) - 1; # Size of the lengths / periods in case you change them
$time = ""; # The string we will hold our times in
while($i >= $n) {
if($diff > $lengths[$i-1]) { # if the difference is greater than the length we are checking... continue
$val = floor($diff / $lengths[$i-1]); # 65 / 60 = 1. That means one minute. 130 / 60 = 2. Two minutes.. etc
$time .= $val ." ". $periods[$i-1].($val > 1 ? 's ' : ' '); # The value, then the name associated, then add 's' if plural
$diff -= ($val * $lengths[$i-1]); # subtract the values we just used from the overall diff so we can find the rest of the information
if(!$detailed) { $i = 0; } # if detailed is turn off (default) only show the first set found, else show all information
}
$i--;
}
# Basic error checking.
if($time == "") {
return "Error-- Unable to calculate time.";
} else {
return $time.$action;
}
}
Now you can specify where you want to stop. Example
timeDiff($yourtimestamp,1,4); //Stops after days (no hours, minutes, seconds)
timeDiff($yourtimestamp,1,5); //Stops after hours
sunjith
07-Jun-2007 04:57
07-Jun-2007 04:57
In ron's script, the while loop condition should be ($i >0). Otherwise, the index $lengths goes to -1 which will show an error.
ron at sdcausa dot org
01-Jun-2007 10:26
01-Jun-2007 10:26
Improvement on top of shdowhawk at gmail dot com:
1. Calculate the time difference (from start to end)
2. Time can be provided as formatted (e.g. 2005-04-02 12:11:10) or integer (12233455).
3. Provide a short display, e.g. 12h 3m 23s
if (!function_exists('timeDiff')){
function timeDiff($starttime, $endtime, $detailed=false, $short = true){
if(! is_int($starttime)) $starttime = strtotime($starttime);
if(! is_int($endtime)) $endtime = strtotime($endtime);
$diff = ($starttime >= $endtime ? $starttime - $endtime : $endtime - $starttime);
# Set the periods of time
$periods = array("second", "minute", "hour", "day", "week", "month", "year", "decade");
$lengths = array(1, 60, 3600, 86400, 604800, 2630880, 31570560, 315705600);
if($short){
$periods = array("s", "m", "h", "d", "m", "y");
$lengths = array(1, 60, 3600, 86400, 2630880, 31570560);
}
# Go from decades backwards to seconds
$i = sizeof($lengths) - 1; # Size of the lengths / periods in case you change them
$time = ""; # The string we will hold our times in
while($i >= 0) {
if($diff > $lengths[$i-1]) { # if the difference is greater than the length we are checking... continue
$val = floor($diff / $lengths[$i-1]); # 65 / 60 = 1. That means one minute. 130 / 60 = 2. Two minutes.. etc
$time .= $val . ($short ? '' : ' ') . $periods[$i-1] . ((!$short && $val > 1) ? 's ' : ' '); # The value, then the name associated, then add 's' if plural
$diff -= ($val * $lengths[$i-1]); # subtract the values we just used from the overall diff so we can find the rest of the information
if(!$detailed) { $i = 0; } # if detailed is turn off (default) only show the first set found, else show all information
}
$i--;
}
return $time;
}
}
shdowhawk at gmail dot com
19-May-2007 03:40
19-May-2007 03:40
I modified the timeDiff scripts from what other people just wrote. I added my little twist onto it =)
Basically... now you can add in a detailed option. By default it is turned off, so we get the .. 1 hour ago .. or .. 2 weeks away.
By calling timeDiff($timestamp,1) ... or timeDiff($timeStamp,true) .. we can now get a detailed count down. Ex: 1 hour 7 minutes 47 seconds ago
function timeDiff($timestamp,$detailed=false){
$now = time();
#If the difference is positive "ago" - negative "away"
($timestamp >= $now) ? $action = 'away' : $action = 'ago';
$diff = ($action == 'away' ? $timestamp - $now : $now - $timestamp);
# Set the periods of time
$periods = array("second", "minute", "hour", "day", "week", "month", "year", "decade");
$lengths = array(1, 60, 3600, 86400, 604800, 2630880, 31570560, 315705600);
# Go from decades backwards to seconds
$i = sizeof($lengths) - 1; # Size of the lengths / periods in case you change them
$time = ""; # The string we will hold our times in
while($i >= 0) {
if($diff > $lengths[$i-1]) { # if the difference is greater than the length we are checking... continue
$val = floor($diff / $lengths[$i-1]); # 65 / 60 = 1. That means one minute. 130 / 60 = 2. Two minutes.. etc
$time .= $val ." ". $periods[$i-1].($val > 1 ? 's ' : ' '); # The value, then the name associated, then add 's' if plural
$diff -= ($val * $lengths[$i-1]); # subtract the values we just used from the overall diff so we can find the rest of the information
if(!$detailed) { $i = 0; } # if detailed is turn off (default) only show the first set found, else show all information
}
$i--;
}
# Basic error checking.
if($time == "") {
return "Error-- Unable to calculate time.";
} else {
return $time.$action;
}
}
joncampell at gmail dot com
08-May-2007 10:07
08-May-2007 10:07
Time difference both forward and backward, based on tristan's TimeAgo() function :)
function timeDiff($timestamp){
$now = time();
//If the difference is positive "ago" - negative "away"
($timestamp >= $now) ? $action = 'away' : $action = 'ago';
switch($action) {
case 'away':
$diff = $timestamp - $now;
break;
case 'ago':
default:
// Determine the difference, between the time now and the timestamp
$diff = $now - $timestamp;
break;
}
// Set the periods of time
$periods = array("second", "minute", "hour", "day", "week", "month", "year", "decade");
// Set the number of seconds per period
$lengths = array(1, 60, 3600, 86400, 604800, 2630880, 31570560, 315705600);
// Go from decades backwards to seconds
for ($val = sizeof($lengths) - 1; ($val >= 0) && (($number = $diff / $lengths[$val]) <= 1); $val--);
// Ensure the script has found a match
if ($val < 0) $val = 0;
// Determine the minor value, to recurse through
$new_time = $now - ($diff % $lengths[$val]);
// Set the current value to be floored
$number = floor($number);
// If required create a plural
if($number != 1) $periods[$val].= "s";
// Return text
$text = sprintf("%d %s ", $number, $periods[$val]);
return $text . $action;
}
If anyone knows of an easier way to do this, please comment.
jason at thinkingman dot org
26-Apr-2007 06:58
26-Apr-2007 06:58
Here you go. You can specify how much you wanna see -- years, weeks, days, hours, minutes or seconds. Returns an Array containing a String along with the individual time values.
Usage:
array calc_tl( int $unixTime, [int $unixTime], [char $selector] )
<?php
function calc_tl($t, $sT = 0, $sel = 'Y') {
$sY = 31536000;
$sW = 604800;
$sD = 86400;
$sH = 3600;
$sM = 60;
if($sT) {
$t = ($sT - $t);
}
if($t <= 0) {
$t = 0;
}
$bs[1] = ('1'^'9'); /* Backspace */
switch(strtolower($sel)) {
case 'y':
$y = ((int)($t / $sY));
$t = ($t - ($y * $sY));
$r['string'] .= "{$y} years{$bs[$y]} ";
$r['years'] = $y;
case 'w':
$w = ((int)($t / $sW));
$t = ($t - ($w * $sW));
$r['string'] .= "{$w} weeks{$bs[$w]} ";
$r['weeks'] = $w;
case 'd':
$d = ((int)($t / $sD));
$t = ($t - ($d * $sD));
$r['string'] .= "{$d} days{$bs[$d]} ";
$r['days'] = $d;
case 'h':
$h = ((int)($t / $sH));
$t = ($t - ($h * $sH));
$r['string'] .= "{$h} hours{$bs[$h]} ";
$r['hours'] = $h;
case 'm':
$m = ((int)($t / $sM));
$t = ($t - ($m * $sM));
$r['string'] .= "{$m} minutes{$bs[$m]} ";
$r['minutes'] = $m;
case 's':
$s = $t;
$r['string'] .= "{$s} seconds{$bs[$s]} ";
$r['seconds'] = $s;
break;
default:
return calc_tl($t);
break;
}
return $r;
}
// A few exaggerated examples:
$startTime = time();
$stopTime = mktime(23,59,59,12,31,2011);
$tY = calc_tl($startTime, $stopTime, 'Y'); // Years (default)
$tD = calc_tl($startTime, $stopTime, 'D'); // Days
$tH = calc_tl($startTime, $stopTime, 'H'); // Hours
print_r($tY);
print_r($tD);
print_r($tH);
?>
OUTPUT
Array
(
[string] => 4 years 35 weeks 6 days 4 hours 54 minutes 33 seconds
[years] => 4
[weeks] => 35
[days] => 6
[hours] => 4
[minutes] => 54
[seconds] => 33
)
Array
(
[string] => 1711 days 4 hours 54 minutes 33 seconds
[days] => 1711
[hours] => 4
[minutes] => 54
[seconds] => 33
)
Array
(
[string] => 41068 hours 54 minutes 33 seconds
[hours] => 41068
[minutes] => 54
[seconds] => 33
)
webmaster[at]auscoder[dot]com
25-Apr-2007 04:36
25-Apr-2007 04:36
In a recent object I had to calculate the time difference between timestamps in a string format, so I wrote this nice little function I'd like to share.
<?php
define('INT_SECOND', 1);
define('INT_MINUTE', 60);
define('INT_HOUR', 3600);
define('INT_DAY', 86400);
define('INT_WEEK', 604800);
function get_formatted_timediff($then, $now = false)
{
$now = (!$now) ? time() : $now;
$timediff = ($now - $then);
$weeks = (int) intval($timediff / INT_WEEK);
$timediff = (int) intval($tim