计算日期java传递的时间

时间:2016-02-16 01:50:52

标签: java android date datetime math

我有一个功能:

  public String getTimePast(Date d) {
  //insertcodehere
 }

它接收消息的日期,并且必须根据特定格式的当前时间返回已经过去的时间。例如,如果它刚刚发布,它会说"现在"

如果是4分钟就会说" 4分钟" 如果它已经23小时它会说" 23hrs" 等

以下是我试图没有运气的方式!我怎么能这样做?谢谢!

public String getTimePast(Date d) {


    Calendar c = Calendar.getInstance();

    int hr = c.get(Calendar.HOUR_OF_DAY);
    int min = c.get(Calendar.MINUTE);
    int day = c.get(Calendar.DAY_OF_MONTH);
    int month = c.get(Calendar.MONTH);
    int year = c.get(Calendar.YEAR);


    if (year == d.getYear()) {
        if (month == d.getMonth()) {
            if (day == d.getDay()) {
                if (hr == d.getHours()) {
                    if (min == d.getMinutes()) {
                        return "Now";
                    } else {
                        return min - d.getMinutes() + "m";
                    }
                } else {
                    return hr - d.getHours() + "hr";

                }
            } else {
                return day - d.getDay() + "d";
            }
        } else {
            return month - d.getMonth() + "m";
        }
    } else {
        return year - d.getYear() + "y";
    }


}

3 个答案:

答案 0 :(得分:4)

如何使用另一个日历对象来简单地找到差异

Calendar now = Calendar.getInstance();
Calendar start = Calendar.getInstance();
start.setTime (d);

long milliseconds1 = start.getTimeInMillis();
  long milliseconds2 = now.getTimeInMillis();
  long diff = milliseconds2 - milliseconds1;
  long diffSeconds = diff / 1000;
  long diffMinutes = diff / (60 * 1000);
  long diffHours = diff / (60 * 60 * 1000);
  long diffDays = diff / (24 * 60 * 60 * 1000);
  System.out.println("\nThe Date Different Example");
  System.out.println("Time in milliseconds: " + diff
 + " milliseconds.");
  System.out.println("Time in seconds: " + diffSeconds
 + " seconds.");
  System.out.println("Time in minutes: " + diffMinutes 
+ " minutes.");
  System.out.println("Time in hours: " + diffHours 
+ " hours.");
  System.out.println("Time in days: " + diffDays 
+ " days.");
  }

请参阅http://www.roseindia.net/java/beginners/DateDifferent.shtml

答案 1 :(得分:2)

您可以使用java.util.concurrent.TimeUnit

long diff = c.getTimeInMillis() - d.getTime();
long minutes = TimeUnit.MILLISECONDS.toMinutes(diff);
long hours = TimeUnit.MILLISECONDS.toHours(diff);
//(...)

他们检查值,例如:

if (minutes > 60) {
    if (hours > 24) {
       // print days
    } else {
       // print hours
    }
} else {
    // print minutes
}

答案 2 :(得分:0)

在Android中执行此操作的最简单,最正确的方法是使用DateUtils中的一个函数,例如getRelativeTimeSpanString()的一个变体。使用哪一个符合您的要求。这应该是首选,因为它将根据当前语言环境格式化字符串,因此它应该以设备支持的任何语言工作。