Solved

Average Tenure Time

Posted on 2013-12-10
7
327 Views
Last Modified: 2013-12-10
I ran a query from MySQL to pull each employee and their start date.

My task is to calculate the average tenure date for the company.

I have a function that tells me how long each employee has been here (i.e, 2 years, 3 months, 4 days), but I need to get the average of that, and that is where I am stuck at...

function employeeLength($time1, $time2, $precision = 3) {
    // If not numeric then convert texts to unix timestamps
    if (!is_int($time1)) {
      $time1 = strtotime($time1);
    }
    if (!is_int($time2)) {
      $time2 = strtotime($time2);
    }
 
    // If time1 is bigger than time2
    // Then swap time1 and time2
    if ($time1 > $time2) {
      $ttime = $time1;
      $time1 = $time2;
      $time2 = $ttime;
    }
 
    // Set up intervals and diffs arrays
    $intervals = array('year','month','day','hour','minute','second');
    $diffs = array();
 
    // Loop thru all intervals
    foreach ($intervals as $interval) {
      // Create temp time from time1 and interval
      $ttime = strtotime('+1 ' . $interval, $time1);
      // Set initial values
      $add = 1;
      $looped = 0;
      // Loop until temp time is smaller than time2
      while ($time2 >= $ttime) {
        // Create new temp time from time1 and interval
        $add++;
        $ttime = strtotime("+" . $add . " " . $interval, $time1);
        $looped++;
      }
 
      $time1 = strtotime("+" . $looped . " " . $interval, $time1);
      $diffs[$interval] = $looped;
    }
 
    $count = 0;
    $times = array();
    // Loop thru all diffs
    foreach ($diffs as $interval => $value) {
      // Break if we have needed precission
      if ($count >= $precision) {
	break;
      }
      // Add value and interval 
      // if value is bigger than 0
      if ($value > 0) {
	// Add s if value is not 1
	if ($value != 1) {
	  $interval .= "s";
	}
	// Add value and interval to times array
	$times[] = $value . " " . $interval;
	$count++;
      }
    }
 
    // Return string with times
    return implode(", ", $times);
  }

$findEmployees = mysql_query("SELECT hr_employeeinfo.respid, doh FROM pr_resp LEFT JOIN hr_employeeinfo ON pr_resp.respid = hr_employeeinfo.respid WHERE pr_resp.hidden = '0' AND activeEmployee = '1' and employeeid > '0'") or die("Cannot get employees: " . mysql_error());

echo '<strong>Total Active Employees: ' . mysql_num_rows($findEmployees) . '</strong><br /><br />';

if(mysql_num_rows($findEmployees) > 0)
	{
	while($row = mysql_fetch_assoc($findEmployees))
		{
		echo $row['respid'] . ' - ' . $row['doh'] . ' - ' . employeeLength($row['doh'], $today) . '<br />';
		}
	}

Open in new window

0
Comment
Question by:t3chguy
  • 3
  • 3
7 Comments
 
LVL 108

Expert Comment

by:Ray Paseur
Comment Utility
You will have some imprecision here because years and months do not have exact numbers of days.  Have a look at practical application number 3 in this article.
http://www.experts-exchange.com/Web_Development/Web_Languages-Standards/PHP/A_201-Handling-date-and-time-in-PHP-and-MySQL.html
0
 
LVL 1

Author Comment

by:t3chguy
Comment Utility
So in doing this...I was able to convert this to days, which is 1926.04054 days.  How can I convert this to years, months, weeks, and days?
0
 
LVL 108

Expert Comment

by:Ray Paseur
Comment Utility
There is no reliable way to get it completely right.  Maybe you can get it close, but you will have to accept that a year, plus or minus a day or two is "close enough."
0
IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

 
LVL 27

Expert Comment

by:yodercm
Comment Utility
I recommend converting each individual tenure to days, which you can do with builtin php functions.  Then add up and average the total days.  Then if you wish, you can convert back to years/months/days.

For your purposes, just use a year as 365 days, so divide your 1926 by 365 to get years.  Take the remainder and divide by 12 to get months.  The remainder of that is days.
0
 
LVL 1

Author Comment

by:t3chguy
Comment Utility
That is what I've done, just questioning the conversion process.  And certainly close enough is close enough.
0
 
LVL 108

Accepted Solution

by:
Ray Paseur earned 500 total points
Comment Utility
Try this.  But understand that there are all kinds of edge cases where your computations will break down.  Here are some of the things that will make this impossible to achieve with perfect accuracy.

How many days in a year?  How about leap year?

How many days in a month?  January has 31, February has 28, or maybe 29 (25% of the time)

How many seconds in an hour?  That one's easy, except at the change of Daylight Savings Time when the number of seconds goes to either zero or 7200.  Unless you're not in an area that observes DST.

Sorry, but there is just no perfect answer.  "Close" is about all you can manage.  One strategy might be this...

if it's less than 30 days, call it in days.
If it's more than 30 days, call it in "months" by dividing by 30
If it's more than 365 days, call it in "years"... etc.

<?php // RAY_temp_t3chguy.php
error_reporting(E_ALL);
echo '<pre>';

// 1926.04054 days
// SEE http://www.experts-exchange.com/Web_Development/Web_Languages-Standards/PHP/Q_28315012.html#a39709516


// STARTING WITH THIS NUMBER OF DAYS
$days  = 1926.0454;

// COMPUTE YEARS
$years = number_format(floor($days / 365.0));

// GET THE REMAINDER
$rem   = $days % 365.0;

// COMPUTE MONTHS FROM THE REMAINDER
$mnths = number_format(floor($rem / 30.0));

echo PHP_EOL . "FROM $days DAYS, WE GET $years YEARS AND $mnths MONTHS";

Open in new window

0
 
LVL 1

Author Closing Comment

by:t3chguy
Comment Utility
That worked great, thank you so much.
0

Featured Post

Highfive + Dolby Voice = No More Audio Complaints!

Poor audio quality is one of the top reasons people don’t use video conferencing. Get the crispest, clearest audio powered by Dolby Voice in every meeting. Highfive and Dolby Voice deliver the best video conferencing and audio experience for every meeting and every room.

Join & Write a Comment

Both Easy and Powerful How easy is PHP? http://lmgtfy.com?q=how+easy+is+php (http://lmgtfy.com?q=how+easy+is+php)  Very easy.  It has been described as "a programming language even my grandmother can use." How powerful is PHP?  http://en.wikiped…
Deprecated and Headed for the Dustbin By now, you have probably heard that some PHP features, while convenient, can also cause PHP security problems.  This article discusses one of those, called register_globals.  It is a thing you do not want.  …
Learn how to match and substitute tagged data using PHP regular expressions. Demonstrated on Windows 7, but also applies to other operating systems. Demonstrated technique applies to PHP (all versions) and Firefox, but very similar techniques will w…
The viewer will learn how to look for a specific file type in a local or remote server directory using PHP.

728 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

15 Experts available now in Live!

Get 1:1 Help Now