Android programming implements tool classes that convert time into a few minutes ago a few days ago and so on

  • 2021-08-17 00:55:00
  • OfStack

This article describes an example of Android programming to transform time into a few minutes ago, a few days ago, and other forms of tool classes. Share it for your reference, as follows:

Description:

When Android developed the client, it was before the time was displayed, such as 10 minutes ago, 8 hours ago, 1 month ago and so on. A tool class is provided below.

Code:


public class TimeUtil {
  private final static long minute = 60 * 1000;// 1 Minutes 
  private final static long hour = 60 * minute;// 1 Hours 
  private final static long day = 24 * hour;// 1 Days 
  private final static long month = 31 * day;//  Month 
  private final static long year = 12 * month;//  Year 
  /**
   *  Returns the date described in text 
   *
   * @param date
   * @return
   */
  public static String getTimeFormatText(Date date) {
    if (date == null) {
      return null;
    }
    long diff = new Date().getTime() - date.getTime();
    long r = 0;
    if (diff > year) {
      r = (diff / year);
      return r + " Years ago ";
    }
    if (diff > month) {
      r = (diff / month);
      return r + " Months ago ";
    }
    if (diff > day) {
      r = (diff / day);
      return r + " Days ago ";
    }
    if (diff > hour) {
      r = (diff / hour);
      return r + " Hours ago ";
    }
    if (diff > minute) {
      r = (diff / minute);
      return r + " Minutes ago ";
    }
    return " Just now ";
  }
}

PS: Here are some online tools for date and time calculation for your reference:

Online date/day calculator:
http://tools.ofstack.com/jisuanqi/date_jisuanqi

Online perpetual calendar:
http://tools.ofstack.com/bianmin/wannianli

Online lunar/solar calendar conversion tool:
http://tools.ofstack.com/bianmin/yinli2yangli

Unix timestamp (timestamp) conversion tool:
http://tools.ofstack.com/code/unixtime

For more readers interested in Android related content, please check the topics on this site: "Summary of Android Date and Time Operation Skills", "Introduction and Advanced Tutorial of Android Development", "Summary of Android Basic Component Usage", "Summary of Android View View Skills", "Summary of Android Layout layout Skills" and "Summary of Android Control Usage"

I hope this article is helpful to everyone's Android programming.


Related articles: