-1

I am receiving the following value from a database which is a millsecond (microtime) value

1369057622.4679

I would like to output this in PHP to be

3 Day's ago

Essentially reading the milliseconds value and converting it to a relative date string, can anyone suggest an easy method to do this.

Justin Erswell
  • 688
  • 7
  • 42
  • 87
  • microtime() gives the current microtime. If you subtract the two, you get the difference in microseconds. You can divide in increments to get days: $days = floor($diff/1000/60/60/24); I added floor so you don't get 3.1231234213451234912873519875 days. – kainaw May 20 '13 at 19:59
  • If you want more flexibility (not just showing days, but weeks or hours it they are more significant), look up [DateTime::Diff](http://www.php.net/manual/en/datetime.diff.php) and the resulting `DateInterval` object. It's more overhead to create the object than simple division, but then you have the tool to format your output any way you want. – Jerry May 20 '13 at 20:23

1 Answers1

1

You may do the following:

$input = 1369057622.4679;

$diff = floor(($input-time())/86400); // calculating the difference

$result = abs($diff) . (abs($diff)==1 ? ' day ':' days ') . ($diff<=0 ? 'ago':'ahead'); // making the result.
echo $result; // output: 1 day ago
HamZa
  • 14,671
  • 11
  • 54
  • 75
  • The diff should be based on microtime(), not time(). The input the user is using is in milliseconds. The time function returns seconds. So, you are subtracting seconds from milliseconds. – kainaw May 21 '13 at 11:59
  • @kainaw That's exactly what I thought on first look, but the input is not in milliseconds, it's in seconds and what comes after the `.` is considered as milliseconds, but since the OP wants the output in days we can "floor" the value because the milliseconds part isn't really relevant. Try to do `echo time();`, the result is `~1369138801`, compare it with `1369057622.4679`. – HamZa May 21 '13 at 12:20