如何将时间转换为"很久以前"在android中

时间:2016-03-08 03:51:10

标签: android datetime time calendar

我的服务器。它返回时间:

"2016-01-24T16:00:00.000Z"

我想要

1:转换为String。

2:我希望它显示"很久以前"从服务器加载时。

请。救救我!

18 个答案:

答案 0 :(得分:20)

我主要看三种方式:

a)使用SimpleDateFormatDateUtils

的内置选项
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
long time = sdf.parse("2016-01-24T16:00:00.000Z").getTime();
long now = System.currentTimeMillis();

CharSequence ago = 
  DateUtils.getRelativeTimeSpanString(time, now, DateUtils.MINUTE_IN_MILLIS);

b)外部资料库ocpsoft/PrettyTime(基于java.util.Date

此处您还必须使用SimpleDateFormat来生成time - 结果,作为“2016-01-24T16:00:00.000Z”的解释。

PrettyTime prettyTime = new PrettyTime(Locale.getDefault());
String ago = prettyTime.format(new Date(time));

c)使用我的库Time4A(重量级,但支持最佳i18n)

Moment moment = Iso8601Format.EXTENDED_DATE_TIME_OFFSET.parse("2016-01-24T16:00:00.000Z");
String ago = PrettyTime.of(Locale.getDefault()).printRelativeInStdTimezone(moment);

答案 1 :(得分:13)

1 - 创建日期格式化程序:

public static final SimpleDateFormat inputFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");

2 - 创建日期对象

String dateStr = "2016-01-24T16:00:00.000Z";
Date date = inputFormat.parse(dateStr);

3 - 使用Android DateUtils创建一个漂亮的显示字符串:

String niceDateStr = DateUtils.getRelativeTimeSpanString(date.getTime() , Calendar.getInstance().getTimeInMillis(), DateUtils.MINUTE_IN_MILLIS);

答案 2 :(得分:11)

这非常简单。我会用我的代码告诉你。

 <android.support.design.widget.TabLayout
                android:id="@+id/test_tab_layout"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_centerHorizontal="true"
                android:background="@color/white"
                android:layout_gravity="bottom"
                android:minHeight="?attr/actionBarSize"
                />

答案 3 :(得分:6)

在Android中,您可以使用 DateUtils.getRelativeTimeSpanString(long timeInMillis),引用https://developer.android.com/reference/android/text/format/DateUtils.html您可以使用该方法的其中一种变体来提高准确性。

答案 4 :(得分:5)

使用@Excelso_Widi代码,我能够克服

我修改了他的代码,还翻译成英文。

public class TimeAgo2 {

public String covertTimeToText(String dataDate) {

    String convTime = null;

    String prefix = "";
    String suffix = "Ago";

    try {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
        Date pasTime = dateFormat.parse(dataDate);

        Date nowTime = new Date();

        long dateDiff = nowTime.getTime() - pasTime.getTime();

        long second = TimeUnit.MILLISECONDS.toSeconds(dateDiff);
        long minute = TimeUnit.MILLISECONDS.toMinutes(dateDiff);
        long hour   = TimeUnit.MILLISECONDS.toHours(dateDiff);
        long day  = TimeUnit.MILLISECONDS.toDays(dateDiff);

        if (second < 60) {
            convTime = second+" Seconds "+suffix;
        } else if (minute < 60) {
            convTime = minute+" Minutes "+suffix;
        } else if (hour < 24) {
            convTime = hour+" Hours "+suffix;
        } else if (day >= 7) {
            if (day > 30) {
                convTime = (day / 30)+" Months "+suffix;
            } else if (day > 360) {
                convTime = (day / 360)+" Years "+suffix;
            } else {
                convTime = (day / 7) + " Week "+suffix;
            }
        } else if (day < 7) {
            convTime = day+" Days "+suffix;
        }

    } catch (ParseException e) {
        e.printStackTrace();
        Log.e("ConvTimeE", e.getMessage());
    }

    return convTime;

}

}

我这样使用它

 String time = jsonObject.getString("date_gmt");
 TimeAgo2 timeAgo2 = new TimeAgo2();
String MyFinalValue = timeAgo2.covertTimeToText(time);

祝您编程愉快,感谢@Excelso_Widi,您是男人眨眼

答案 5 :(得分:4)

private static final int SECOND_MILLIS = 1000;
private static final int MINUTE_MILLIS = 60 * SECOND_MILLIS;
private static final int HOUR_MILLIS = 60 * MINUTE_MILLIS;
private static final int DAY_MILLIS = 24 * HOUR_MILLIS;

private static Date currentDate() {
    Calendar calendar = Calendar.getInstance();
    return calendar.getTime();
}

public static String getTimeAgo(Date date) {
    long time = date.getTime();
    if (time < 1000000000000L) {
        time *= 1000;
    }

    long now = currentDate().getTime();
    if (time > now || time <= 0) {
        return "in the future";
    }

    final long diff = now - time;
    if (diff < MINUTE_MILLIS) {
        return "moments ago";
    } else if (diff < 2 * MINUTE_MILLIS) {
        return "a minute ago";
    } else if (diff < 60 * MINUTE_MILLIS) {
        return diff / MINUTE_MILLIS + " minutes ago";
    } else if (diff < 2 * HOUR_MILLIS) {
        return "an hour ago";
    } else if (diff < 24 * HOUR_MILLIS) {
        return diff / HOUR_MILLIS + " hours ago";
    } else if (diff < 48 * HOUR_MILLIS) {
        return "yesterday";
    } else {
        return diff / DAY_MILLIS + " days ago";
    }
}

只需调用getTimeAgo(timeInDate);

它为我工作。

答案 6 :(得分:3)

步骤1.使用long type

将时间字符串转换为milisecond格式

步骤2.使用下面的代码

 private static final int SECOND_MILLIS = 1000; 
    private static final int MINUTE_MILLIS = 60 * SECOND_MILLIS; 
    private static final int HOUR_MILLIS = 60 * MINUTE_MILLIS; 
    private static final int DAY_MILLIS = 24 * HOUR_MILLIS; 

    public static String getTimeAgo(long time, Context ctx) { 
    if (time < 1000000000000L) { 
    //if timestamp given in seconds, convert to millis time *= 1000; } 
    long now = getCurrentTime(ctx); 
    if (time > now || time <= 0) { return null; } 
// TODO: localize final long diff = now - time; 
if (diff < MINUTE_MILLIS) { return "just now"; } 
    else if (diff < 2 * MINUTE_MILLIS) { return "a minute ago"; } 
    else if (diff < 50 * MINUTE_MILLIS) { return diff / MINUTE_MILLIS + " minutes ago"; } 
    else if (diff < 90 * MINUTE_MILLIS) { return "an hour ago"; } 
    else if (diff < 24 * HOUR_MILLIS) { return diff / HOUR_MILLIS + " hours ago"; } else if (diff < 48 * HOUR_MILLIS) { return "yesterday"; } 
    else { return diff / DAY_MILLIS + " days ago"; } }

//来自google的代码!

答案 7 :(得分:2)

您可以在getlongtoago方法中传递毫秒数,然后返回完美格式化字符串

public static String getlongtoago(long createdAt) {
    DateFormat userDateFormat = new SimpleDateFormat("E MMM dd HH:mm:ss Z yyyy");
    DateFormat dateFormatNeeded = new SimpleDateFormat("MM/dd/yyyy HH:MM:SS");
    Date date = null;
    date = new Date(createdAt);
    String crdate1 = dateFormatNeeded.format(date);

    // Date Calculation
    DateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
    crdate1 = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss").format(date);

    // get current date time with Calendar()
    Calendar cal = Calendar.getInstance();
    String currenttime = dateFormat.format(cal.getTime());

    Date CreatedAt = null;
    Date current = null;
    try {
        CreatedAt = dateFormat.parse(crdate1);
        current = dateFormat.parse(currenttime);
    } catch (java.text.ParseException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    // Get msec from each, and subtract.
    long diff = current.getTime() - CreatedAt.getTime();
    long diffSeconds = diff / 1000;
    long diffMinutes = diff / (60 * 1000) % 60;
    long diffHours = diff / (60 * 60 * 1000) % 24;
    long diffDays = diff / (24 * 60 * 60 * 1000);

    String time = null;
    if (diffDays > 0) {
        if (diffDays == 1) {
            time = diffDays + "day ago ";
        } else {
            time = diffDays + "days ago ";
        }
    } else {
        if (diffHours > 0) {
            if (diffHours == 1) {
                time = diffHours + "hr ago";
            } else {
                time = diffHours + "hrs ago";
            }
        } else {
            if (diffMinutes > 0) {
                if (diffMinutes == 1) {
                    time = diffMinutes + "min ago";
                } else {
                    time = diffMinutes + "mins ago";
                }
            } else {
                if (diffSeconds > 0) {
                    time = diffSeconds + "secs ago";
                }
            }

        }

    }
    return time;
}

答案 8 :(得分:1)

您要转换的内容是=STDEV.S(IF($C$2:$C$5="Female",$B$2:$B$5)) 兼容格式。转换此内容的最简单方法是使用Joda-Time library for Android。

将其添加到项目后,您可以使用此代码提取确切的日期!

ISO 8601

另外,请参阅this以格式化您首选的日期 希望它有所帮助!

答案 9 :(得分:1)

public class TimeUtility {

public String covertTimeToText(String dataDate) {

    String convTime = null;

    try {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date pasTime = dateFormat.parse(dataDate);

        Date nowTime = new Date();

        long dateDiff = nowTime.getTime() - pasTime.getTime();

        long detik = TimeUnit.MILLISECONDS.toSeconds(dateDiff);
        long menit = TimeUnit.MILLISECONDS.toMinutes(dateDiff);
        long jam   = TimeUnit.MILLISECONDS.toHours(dateDiff);
        long hari  = TimeUnit.MILLISECONDS.toDays(dateDiff);

        if (detik < 60) {
            convTime = detik+"detik lalu";
        } else if (menit < 60) {
            convTime = menit+"menit lalu";
        } else if (jam < 24) {
            convTime = jam+"jam lalu";
        } else if (hari >= 7) {
            if (hari > 30) {
                convTime = (hari / 30)+"bulan lalu";
            } else if (hari > 360) {
                convTime = (hari / 360)+"tahun lalu";
            } else {
                convTime = (hari / 7) + "minggu lalu";
            }
        } else if (hari < 7) {
            convTime = hari+"hari lalu";
        }

    } catch (ParseException e) {
        e.printStackTrace();
        Log.e("ConvTimeE", e.getMessage());
    }

    return convTime;

  }

}

答案 10 :(得分:1)

对于Kotlin,您可以使用此扩展功能。

fun Date.getTimeAgo(): String {
    val calendar = Calendar.getInstance()
    calendar.time = this

    val year = calendar.get(Calendar.YEAR)
    val month = calendar.get(Calendar.MONTH)
    val day = calendar.get(Calendar.DAY_OF_MONTH)
    val hour = calendar.get(Calendar.HOUR_OF_DAY)
    val minute = calendar.get(Calendar.MINUTE)

    val currentCalendar = Calendar.getInstance()

    val currentYear = currentCalendar.get(Calendar.YEAR)
    val currentMonth = currentCalendar.get(Calendar.MONTH)
    val currentDay = currentCalendar.get(Calendar.DAY_OF_MONTH)
    val currentHour = currentCalendar.get(Calendar.HOUR_OF_DAY)
    val currentMinute = currentCalendar.get(Calendar.MINUTE)

    return if (year < currentYear ) {
        val interval = currentYear - year
        if (interval == 1) "$interval year ago" else "$interval years ago"
    } else if (month < currentMonth) {
        val interval = currentMonth - month
        if (interval == 1) "$interval month ago" else "$interval months ago"
    } else  if (day < currentDay) {
        val interval = currentDay - day
        if (interval == 1) "$interval day ago" else "$interval days ago"
    } else if (hour < currentHour) {
        val interval = currentHour - hour
        if (interval == 1) "$interval hour ago" else "$interval hours ago"
    } else if (minute < currentMinute) {
        val interval = currentMinute - minute
        if (interval == 1) "$interval minute ago" else "$interval minutes ago"
    } else {
        "a moment ago"
    }
}

// To use it
val timeAgo = someDate.getTimeAgo()

答案 11 :(得分:1)

您可以选择希望两种方法都可以测试并且可以正常工作的类型格式。

/ *

* It's return date  before one week timestamp
*  like return
*  1 day ago
*  2 days ago
*  5 days ago
*  21 April 2019
*

* */
public static String getTimeAgoDate(long pastTimeStamp) {

    // for 2 min ago   use  DateUtils.MINUTE_IN_MILLIS
    // for 2 sec ago   use  DateUtils.SECOND_IN_MILLIS
    // for 1 hours ago use  DateUtils.HOUR_IN_MILLIS

    long now = System.currentTimeMillis();

    if (now - pastTimeStamp < 1000) {
        pastTimeStamp = pastTimeStamp + 1000;
    }
    CharSequence ago =
            DateUtils.getRelativeTimeSpanString(pastTimeStamp, now, DateUtils.SECOND_IN_MILLIS);
    return ago.toString();
}


/*
 *
 * It's return date  before one week timestamp
 *
 *  like return
 *
 *  1 day ago
 *  2 days ago
 *  5 days ago
 *  2 weeks ago
 *  2 months ago
 *  2 years ago
 *
 *
 * */

public static String getTimeAgo(long mReferenceTime) {

    long now = System.currentTimeMillis();
    final long diff = now - mReferenceTime;
    if (diff < android.text.format.DateUtils.WEEK_IN_MILLIS) {
        return (diff <= 1000) ?
                "just now" :
                android.text.format.DateUtils.getRelativeTimeSpanString(mReferenceTime, now, DateUtils.MINUTE_IN_MILLIS,
                        DateUtils.FORMAT_ABBREV_RELATIVE).toString();
    } else if (diff <= 4 * android.text.format.DateUtils.WEEK_IN_MILLIS) {
        int week = (int)(diff / (android.text.format.DateUtils.WEEK_IN_MILLIS));
        return  week>1?week+" weeks ago":week+" week ago";
    } else if (diff < android.text.format.DateUtils.YEAR_IN_MILLIS) {
        int month = (int)(diff / (4 * android.text.format.DateUtils.WEEK_IN_MILLIS));
        return  month>1?month+" months ago":month+" month ago";
    } else {
        int year = (int) (diff/DateUtils.YEAR_IN_MILLIS);
        return year>1?year+" years ago":year+" year ago";
    }
}

谢谢

答案 12 :(得分:0)

当我遍历所有答案时,有多种方法可以获取此查询的解决方案,无论如何,以下答案不需要任何第三方模块或任何本机util类,您可以从本机Java获取结果使用以下技术,这也是内存优化的答案,不会消耗太多内存。

用法:

HumanDateUtils.durationFromNow(startDate)

您可以根据需要通过添加ago or seen自定义此方法。

import java.util.Date;

public class HumanDateUtils {

    public static String durationFromNow(Date startDate) {

        long different = System.currentTimeMillis() - startDate.getTime();

        long secondsInMilli = 1000;
        long minutesInMilli = secondsInMilli * 60;
        long hoursInMilli = minutesInMilli * 60;
        long daysInMilli = hoursInMilli * 24;

        long elapsedDays = different / daysInMilli;
        different = different % daysInMilli;

        long elapsedHours = different / hoursInMilli;
        different = different % hoursInMilli;

        long elapsedMinutes = different / minutesInMilli;
        different = different % minutesInMilli;

        long elapsedSeconds = different / secondsInMilli;

        String output = "";
        if (elapsedDays > 0) output += elapsedDays + "days ";
        if (elapsedDays > 0 || elapsedHours > 0) output += elapsedHours + " hours ";
        if (elapsedHours > 0 || elapsedMinutes > 0) output += elapsedMinutes + " minutes ";
        if (elapsedMinutes > 0 || elapsedSeconds > 0) output += elapsedSeconds + " seconds";

        return output;
    }
}

输出:
12天12小时25分钟4秒

参考:Human Readable Date - Java

答案 13 :(得分:0)

修改以上答案:

public class TimeAgo {



   public String covertTimeToText(String dataDate) {

        String convertTime = null;
    String suffix = "ago";

    try {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());
        Date pasTime = dateFormat.parse(dataDate);

        Date nowTime = new Date();

        long dateDiff = nowTime.getTime() - pasTime.getTime();

        long second = TimeUnit.MILLISECONDS.toSeconds(dateDiff);
        long minute = TimeUnit.MILLISECONDS.toMinutes(dateDiff);
        long hour = TimeUnit.MILLISECONDS.toHours(dateDiff);
        long day = TimeUnit.MILLISECONDS.toDays(dateDiff);

        if (second < 60) {
            if (second == 1) {
                convertTime = second + " second " + suffix;
            } else {
                convertTime = second + " seconds " + suffix;
            }
        } else if (minute < 60) {
            if (minute == 1) {
                convertTime = minute + " minute " + suffix;
            } else {
                convertTime = minute + " minutes " + suffix;
            }
        } else if (hour < 24) {
            if (hour == 1) {
                convertTime = hour + " hour " + suffix;
            } else {
                convertTime = hour + " hours " + suffix;
            }
        } else if (day >= 7) {
            if (day >= 365) {
                long tempYear = day / 365;
                if (tempYear == 1) {
                    convertTime = tempYear + " year " + suffix;
                } else {
                    convertTime = tempYear + " years " + suffix;
                }
            } else if (day >= 30) {
                long tempMonth = day / 30;
                if (tempMonth == 1) {
                    convertTime = (day / 30) + " month " + suffix;
                } else {
                    convertTime = (day / 30) + " months " + suffix;
                }
            } else {
                long tempWeek = day / 7;
                if (tempWeek == 1) {
                    convertTime = (day / 7) + " week " + suffix;
                } else {
                    convertTime = (day / 7) + " weeks " + suffix;
                }
            }
        } else {
            if (day == 1) {
                convertTime = day + " day " + suffix;
            } else {
                convertTime = day + " days " + suffix;
            }
        }

    } catch (ParseException e) {
        e.printStackTrace();
        Log.e("TimeAgo", e.getMessage() + "");
    }
    return convertTime;
   }

}

答案 14 :(得分:0)

请检查下面的代码,以模块化和可重用的方式完美地完成此操作,这也将使您将来的时间回来,例如 5分钟后。首先,您需要在我下面提到的项目中创建UnixToHuman类。然后,您需要通过

将服务器返回的字符串转换为UNIX时间戳。
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
long time = sdf.parse("2016-01-24T16:00:00.000Z").getTime();

然后,您只需要调用函数UnixToHuman.getTimeAgo(long time),其中time是您的UNIX时间,它将返回所需的字符串。 UnixToHuman.java

public class UnixToHuman {
    private static final int SECOND_MILLIS = 1000;
    private static final int MINUTE_MILLIS = 60 * SECOND_MILLIS;
    private static final int HOUR_MILLIS = 60 * MINUTE_MILLIS;
    private static final int DAY_MILLIS = 24 * HOUR_MILLIS;
    private static final int WEEK_MILLIS = 7 * DAY_MILLIS ;

    public static String getTimeAgo(long time) {
        if (time < 1000000000000L) {
            // if timestamp given in seconds, convert to millis
            time *= 1000;
        }

        long now =System.currentTimeMillis();;


        long diff = now - time;
        if(diff>0) {


            if (diff < MINUTE_MILLIS) {
                return "just now";
            } else if (diff < 2 * MINUTE_MILLIS) {
                return "a minute ago";
            } else if (diff < 50 * MINUTE_MILLIS) {
                return diff / MINUTE_MILLIS + " minutes ago";
            } else if (diff < 90 * MINUTE_MILLIS) {
                return "an hour ago";
            } else if (diff < 24 * HOUR_MILLIS) {
                return diff / HOUR_MILLIS + " hours ago";
            } else if (diff < 48 * HOUR_MILLIS) {
                return "yesterday";
            } else if (diff < 7 * DAY_MILLIS) {
                return diff / DAY_MILLIS + " days ago";
            } else if (diff < 2 * WEEK_MILLIS) {
                return "a week ago";
            } else if (diff < WEEK_MILLIS * 3) {
                return diff / WEEK_MILLIS + " weeks ago";
            } else {
                java.util.Date date = new java.util.Date((long) time);
                return date.toString();
            }

        }
        else {

            diff=time-now;
            if (diff < MINUTE_MILLIS) {
                return "this minute";
            } else if (diff < 2 * MINUTE_MILLIS) {
                return "a minute later";
            } else if (diff < 50 * MINUTE_MILLIS) {
                return diff / MINUTE_MILLIS + " minutes later";
            } else if (diff < 90 * MINUTE_MILLIS) {
                return "an hour later";
            } else if (diff < 24 * HOUR_MILLIS) {
                return diff / HOUR_MILLIS + " hours later";
            } else if (diff < 48 * HOUR_MILLIS) {
                return "tomorrow";
            } else if (diff < 7 * DAY_MILLIS) {
                return diff / DAY_MILLIS + " days later";
            } else if (diff < 2 * WEEK_MILLIS) {
                return "a week later";
            } else if (diff < WEEK_MILLIS * 3) {
                return diff / WEEK_MILLIS + " weeks later";
            } else {
                java.util.Date date = new java.util.Date((long) time);
                return date.toString();
            }
        }

    }
}

答案 15 :(得分:0)

科林版

private const val SECOND_MILLIS = 1000
private const val MINUTE_MILLIS = 60 * SECOND_MILLIS
private const val HOUR_MILLIS = 60 * MINUTE_MILLIS
private const val DAY_MILLIS = 24 * HOUR_MILLIS

private fun currentDate(): Date {
    val calendar = Calendar.getInstance()
    return calendar.time
}

fun getTimeAgo(date: Date): String {
    var time = date.time
    if (time < 1000000000000L) {
        time *= 1000
    }

    val now = currentDate().time
    if (time > now || time <= 0) {
        return "in the future"
    }

    val diff = now - time
    return when {
        diff < MINUTE_MILLIS -> "moments ago"
        diff < 2 * MINUTE_MILLIS -> "a minute ago"
        diff < 60 * MINUTE_MILLIS -> "${diff / MINUTE_MILLIS} minutes ago"
        diff < 2 * HOUR_MILLIS -> "an hour ago"
        diff < 24 * HOUR_MILLIS -> "${diff / HOUR_MILLIS} hours ago"
        diff < 48 * HOUR_MILLIS -> "yesterday"
        else -> "${diff / DAY_MILLIS} days ago"
    }
}

答案 16 :(得分:0)

太晚了,试试这个,

 public static String parseDate(String givenDateString) {
    if (givenDateString.equalsIgnoreCase("")) {
        return "";
    }

    long timeInMilliseconds=0;
    SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy hh:mm:ss");
    try {

        Date mDate = sdf.parse(givenDateString);
        timeInMilliseconds = mDate.getTime();
        System.out.println("Date in milli :: " + timeInMilliseconds);
    } catch (ParseException e) {
        e.printStackTrace();
    }


    String result = "now";
    SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy hh:mm:ss");

    String todayDate = formatter.format(new Date());
    Calendar calendar = Calendar.getInstance();

    long dayagolong =  timeInMilliseconds;
    calendar.setTimeInMillis(dayagolong);
    String agoformater = formatter.format(calendar.getTime());

    Date CurrentDate = null;
    Date CreateDate = null;

    try {
        CurrentDate = formatter.parse(todayDate);
        CreateDate = formatter.parse(agoformater);

        long different = Math.abs(CurrentDate.getTime() - CreateDate.getTime());

        long secondsInMilli = 1000;
        long minutesInMilli = secondsInMilli * 60;
        long hoursInMilli = minutesInMilli * 60;
        long daysInMilli = hoursInMilli * 24;

        long elapsedDays = different / daysInMilli;
        different = different % daysInMilli;

        long elapsedHours = different / hoursInMilli;
        different = different % hoursInMilli;

        long elapsedMinutes = different / minutesInMilli;
        different = different % minutesInMilli;

        long elapsedSeconds = different / secondsInMilli;

        different = different % secondsInMilli;
        if (elapsedDays == 0) {
            if (elapsedHours == 0) {
                if (elapsedMinutes == 0) {
                    if (elapsedSeconds < 0) {
                        return "0" + " s";
                    } else {
                        if (elapsedDays > 0 && elapsedSeconds < 59) {
                            return "now";
                        }
                    }
                } else {
                    return String.valueOf(elapsedMinutes) + "mins ago";
                }
            } else {
                return String.valueOf(elapsedHours) + "hr ago";
            }

        } else {
            if (elapsedDays <= 29) {
                return String.valueOf(elapsedDays) + "d ago";

            }
            else if (elapsedDays > 29 && elapsedDays <= 58) {
                return "1Mth ago";
            }
            if (elapsedDays > 58 && elapsedDays <= 87) {
                return "2Mth ago";
            }
            if (elapsedDays > 87 && elapsedDays <= 116) {
                return "3Mth ago";
            }
            if (elapsedDays > 116 && elapsedDays <= 145) {
                return "4Mth ago";
            }
            if (elapsedDays > 145 && elapsedDays <= 174) {
                return "5Mth ago";
            }
            if (elapsedDays > 174 && elapsedDays <= 203) {
                return "6Mth ago";
            }
            if (elapsedDays > 203 && elapsedDays <= 232) {
                return "7Mth ago";
            }
            if (elapsedDays > 232 && elapsedDays <= 261) {
                return "8Mth ago";
            }
            if (elapsedDays > 261 && elapsedDays <= 290) {
                return "9Mth ago";
            }
            if (elapsedDays > 290 && elapsedDays <= 319) {
                return "10Mth ago";
            }
            if (elapsedDays > 319 && elapsedDays <= 348) {
                return "11Mth ago";
            }
            if (elapsedDays > 348 && elapsedDays <= 360) {
                return "12Mth ago";
            }

            if (elapsedDays > 360 && elapsedDays <= 720) {
                return "1 year ago";
            }
        }

    } catch (java.text.ParseException e) {
        e.printStackTrace();
    }
    return result;
}

答案 17 :(得分:0)

试试这个

我在尝试将时间戳转换为时间格式时面临同样的问题(未处理的execption java.text.ParseExecption ),在做完R&amp; D后我终于得到了解决方案......现在这个错误已经解决了

  • 在您的bulid.gradle(模块:应用)中添加此(编译'org.ocpsoft.prettytime:prettytime:4.0.1.Final')依赖关系并同步您的项目
  • 添加此依赖项后粘贴此方法并将其调用到您想要的位置(Log.e(“TAG”,“ConvertTimeStampintoAgo:”+ ConvertTimeStampintoAgo(1320917972));)

    public static String ConvertTimeStampintoAgo(Long timeStamp)
    {
    try
    {
        Calendar cal = Calendar.getInstance(Locale.getDefault());
        cal.setTimeInMillis(timeStamp);
        String date = android.text.format.DateFormat.format("yyyy-MM-dd HH:mm:ss", cal).toString();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());
        Date dateObj = sdf.parse(date);
        PrettyTime p = new PrettyTime();
        return p.format(dateObj);
    }
    catch (Exception e)
    {
        e.printStackTrace();
    }
    return "";
    }
    

    注意它会显示

  • 时刻(当前时间)

  • 分钟前

  • 一天前