如何知道json日期的经过时间

时间:2017-05-14 07:28:14

标签: android json date time elapsedtime

我有一个项目列表,它通过json链接从服务器获取数据,其中一个属性是创建项目的日期/时间,如下所示:

created_at: "2017-05-13T08:53:40Z"

我想在textview上显示每个项目的顶部,但是在Facebook状态,如format =>

1分钟前| 2小时前| 4天前| 5个月前等..

我该怎么办。!?

更新

这是我最近的尝试。 '_'

  public String getOrderTime() {

    GregorianCalendar now = new GregorianCalendar();
    Date time = getTime(); // getTime is coming from json

    Log.i("Json Time ", time + "");

    long MILLIS_PER_DAY = 24 * 60 * 60 * 1000;
    long timePortion = time.getTime() % MILLIS_PER_DAY;

    Log.i("New Json Time ", timePortion + "");
    Log.i("Time Now ", now.getTimeInMillis() + "");

    String elapsed_time = DateUtils.getRelativeTimeSpanString(
            timePortion,
            now.getTimeInMillis(),
            DateUtils.SECOND_IN_MILLIS)
            .toString();

    Log.i("Elapsed Time", elapsed_time);

    return elapsed_time;
 }

以下是日志,显然出现了问题

I/Json Time: Sun May 14 03:27:22 EDT 2017
I/New Json Time: 26842000
I/Time Now: 1494747376756
I/Elapsed Time: Jan 1, 1970

更新2

新方法

  public String getOrderTime() {

    long end_time = theTime().getTime();  // json time
    long right_now = System.currentTimeMillis(); // right now

    Log.i("Time Now ", right_now + "");
    Log.i("Json Time ", end_time + "");

    long difference = right_now - end_time;
    Log.i("Elapsed Time", difference + "");

    if (difference < 60) {

        Log.i("Time in Minutes", difference + "m");
        return  difference + "m";

    } else {
        difference /= 60;
        if (difference < 24) {

            Log.i("Time in Hours", difference + "h");
            return difference + "h";

        } else {
            difference /= 30;

            Log.i("Time in Months", difference + "mo");
            return difference + "mo";
        }
    }

日志

     I/Time Now: 1494762022853
     I/Json Time: 1494758529000
     I/Elapsed Time: 3493853
     I/Time in Months: 1941mo

1 个答案:

答案 0 :(得分:0)

首先,您需要计算两个日期之间的difference,即您的指定日期和当前日期:

long difference = endDate.getTime() - startDate.getTime()

difference将以毫秒为单位保持差异

difference /= 60000; //minutes

if (difference < 60) {
    //minutes
} else {
    difference /= 60; //hours
    if (difference < 24) {
        //hours
    } else {
        difference /= 24; //days
        if (difference < 30) {
            //days
        } else {
            //months
        }
    }
}