0

I receive a specific datetime value from my MySQL Database, and I want to convert it into formats like:

a while ago

2 hours ago

3 days ago

a month ago

it's been years (for above 2 year)

I am using PHP for this web service, this is a iOS app, but as I will send the JSON string to device. Should I convert the format in API itself or at device's end. and I am having to do it manually, Is there any sort of shortcut for this.

I have thought of using the if-else ladder logic, but it seems pretty mechanical. Any idea of any other 3rd party API.

Community
  • 1
  • 1
vaibhav
  • 396
  • 2
  • 17
  • I think everybody does it with if else – Geru May 17 '14 at 17:08
  • What you want calls **Human readable Time**. See WordPress for example (`human_time_diff( $from, $to = '' )`): https://core.trac.wordpress.org/browser/tags/3.9.1/src/wp-includes/formatting.php#L0 – Adrian Preuss May 17 '14 at 18:27
  • http://stackoverflow.com/questions/8629788/php-strtotime-reverse – rich remer May 17 '14 at 18:30
  • 1
    It would probably be better to transmit the original timestamp and do the conversion on the client. This will give you the ability to display the full timestamp if the user wants to see it, filter on ranges client-side if necessary, re-calculate the fuzzy time if the data is cached / displayed for a long time, etc. – nobody May 17 '14 at 18:43

1 Answers1

1

so far there is no such API or web-services i think` and everybody does it this way :

const int SECOND = 1;
const int MINUTE = 60 * SECOND;
const int HOUR = 60 * MINUTE;
const int DAY = 24 * HOUR;
const int MONTH = 30 * DAY;

if (delta < 0)
{
  return "not yet";
}
if (delta < 1 * MINUTE)
{
  return ts.Seconds == 1 ? "one second ago" : ts.Seconds + " seconds ago";
}
if (delta < 2 * MINUTE)
{
  return "a minute ago";
}
if (delta < 45 * MINUTE)
{
  return ts.Minutes + " minutes ago";
}
if (delta < 90 * MINUTE)
{
  return "an hour ago";
}
if (delta < 24 * HOUR)
{
  return ts.Hours + " hours ago";
}
if (delta < 48 * HOUR)
{
  return "yesterday";
}
if (delta < 30 * DAY)
{
  return ts.Days + " days ago";
}
if (delta < 12 * MONTH)
{
  int months = Convert.ToInt32(Math.Floor((double)ts.Days / 30));
  return months <= 1 ? "one month ago" : months + " months ago";
}
else
{
  int years = Convert.ToInt32(Math.Floor((double)ts.Days / 365));
  return years <= 1 ? "one year ago" : years + " years ago";
}

if anybody has better idea.. let's see..