Last Updated: February 25, 2016
·
385
· slugmandrew

Render hangouts / facebook chat style dates (Java GWT example)

Simple function to convert dates into something more easily readable by humans.

Will show things like:

  • Now (if under a minute)
  • 12 mins ago (if under an hour)
  • 15:47 (if over an hour on the same day)
  • 12 Jun, 15:47 (if on a day before today)

Code:

public static String getReadableTimeSince(Date input)
{
    Date now = new Date();

    if(now.before(input))
    {
        Log.error("Date cannot be in the future:" + input);
        return "";
    }

    if(CalendarUtil.isSameDate(input, now))
    {
        Long diff = now.getTime() - input.getTime();

        if(TimeUnit.MILLISECONDS.toSeconds(diff) < 60)
        {
            return "Now";
        }
        else if(TimeUnit.MILLISECONDS.toMinutes(diff) < 60)
        {
            long mins = TimeUnit.MILLISECONDS.toMinutes(diff);

            return mins == 1 ? mins + " min" : mins + " mins";
        }
        else if(TimeUnit.MILLISECONDS.toHours(diff) < 24)
        {
            return DateTimeFormat.getFormat("kk:mm").format(input);
        }

    }
    else if(CalendarUtil.getDaysBetween(input, now) > 0)
    {
        // message was before today
        return DateTimeFormat.getFormat("dd MMM, kk:mm").format(input);
    }

    return "";
}