【问题标题】:How to convert time to " time ago " in android如何在android中将时间转换为“时间前”
【发布时间】:2016-06-21 21:08:29
【问题描述】:

我的服务器。返回时间:

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

我想要

1 : 转换为字符串。

2:我希望它在从服务器加载时显示“时间前”。

请。帮帮我!

【问题讨论】:

  • 哥们,你必须展示你试过的代码,否则你很难在这里得到帮助
  • 我不知道这项工作:(
  • @anhthangBui 你解决了吗?

标签: android datetime time calendar


【解决方案1】:

我主要看到三种方式:

a) 使用 SimpleDateFormatDateUtils 的内置选项

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
  sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
  try {
         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);
        } catch (ParseException e) {
            e.printStackTrace();
        }

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

在这里您也必须使用SimpleDateFormat 来生成time-result 作为“2016-01-24T16:00:00.000Z”的解释。

在您的应用中导入以下库

implementation 'org.ocpsoft.prettytime:prettytime:4.0.1.Final'

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);

【讨论】:

  • Unhandled execption java.text.ParseExecption on line long time = sdf.parse("2016-01-24T16:00:00.000Z").getTime(); 怎么了?
  • @MichaelJulyusChristopherM。方法parse(...) 被声明为抛出一个检查异常,因此调用parse(...) 的测试方法也必须声明它(或者以合理的方式捕获并处理但不忽略它,例如日志记录)。跨度>
  • getRelativeTimeSpanString 仅适用于小于一周的日期差异。文档没有说明这一点,但是当您使用 API 时,您会发现这个讨厌的问题。这在 Stackoverflow 的其他地方都有记录。
  • @AndroidDev getRelativeTimeSpanString() 的文档确实说明了 minResolution 参数的周限制:“通过 0、MINUTE_IN_MILLIS、HOUR_IN_MILLIS、DAY_IN_MILLIS、WEEK_IN_MILLIS 之一”所以它不是我的回答是DateUtil-API。 OP 甚至没有提出克服这一限制的要求。所以我认为我的回答仍然有效,此外,它提供了 Time4A 的一流替代方案,它也可以呈现几个月或几年的差异。
【解决方案2】:

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);

【讨论】:

  • 这是最好的方法,imo。当Android为此内置方法时,无需自行检查天,小时和分钟
  • 它实际上并没有创建一个 "ago" 字符串。
  • 我想知道。该答案已在我发布近 9 个月后发布,但没有添加任何新内容(看起来几乎像我的答案中 a 部分的副本),甚至包含一个严重错误(我的答案中设置格式化程序上的时区偏移的行丢失了!)。
  • 推测@MenoHochschild,但这可能是因为 Stack Overflow 上答案的默认排序现在是“Active”而不是“Votes”,所以你的答案正在冒泡。
  • 谢谢,如何翻译 niceDateStr?
【解决方案3】:

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

package com.example;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.TimeUnit;

public class TimeShow
{
    public static void main(String[] args) {
        try 
        {
            SimpleDateFormat format = new SimpleDateFormat("yyyy.MM.dd G 'at' HH:mm:ss");
            Date past = format.parse("2016.02.05 AD at 23:59:30");
            Date now = new Date();
            long seconds=TimeUnit.MILLISECONDS.toSeconds(now.getTime() - past.getTime());
            long minutes=TimeUnit.MILLISECONDS.toMinutes(now.getTime() - past.getTime());
            long hours=TimeUnit.MILLISECONDS.toHours(now.getTime() - past.getTime());
            long days=TimeUnit.MILLISECONDS.toDays(now.getTime() - past.getTime());
//
//          System.out.println(TimeUnit.MILLISECONDS.toSeconds(now.getTime() - past.getTime()) + " milliseconds ago");
//          System.out.println(TimeUnit.MILLISECONDS.toMinutes(now.getTime() - past.getTime()) + " minutes ago");
//          System.out.println(TimeUnit.MILLISECONDS.toHours(now.getTime() - past.getTime()) + " hours ago");
//          System.out.println(TimeUnit.MILLISECONDS.toDays(now.getTime() - past.getTime()) + " days ago");

            if(seconds<60)
            {
                System.out.println(seconds+" seconds ago");
            }
            else if(minutes<60)
            {
                System.out.println(minutes+" minutes ago");
            }
            else if(hours<24)
            {
                System.out.println(hours+" hours ago");
            }
            else 
            {
                System.out.println(days+" days ago");
            }
        }
        catch (Exception j){
            j.printStackTrace();
        }
    }
}

【讨论】:

  • 你好。请帮我解析:“ 2016-01-24T16:00:00.000Z 。非常感谢!
  • 你不需要解析。我正在使用解析,因为我正在为您创建演示日期格式。我认为您已经有了日期格式,只需将其转换为字符串然后为当前日期创建 Date 对象。在此之后,只需使用我的逻辑,它将为您提供您想要达到的完美结果。
【解决方案4】:

使用@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 > 360) {
                    convTime = (day / 360) + " Years " + suffix;
                } else if (day > 30) {
                    convTime = (day / 30) + " Months " + 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 你这个人wink

【讨论】:

    【解决方案5】:

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

    【讨论】:

    • 看起来这只适用于一周内的时间戳
    【解决方案6】:

    Kotlin 版本

    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"
        }
    }
    

    【讨论】:

      【解决方案7】:

      对于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()
      

      【讨论】:

      • 你能发布 Java 代码而不是 Kotlin 吗?
      • 太棒了,谢谢。
      【解决方案8】:
      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);

      它对我有用。

      【讨论】:

      • SECOND_MILLIS 的值是多少
      • @SAndroidD private static final int SECOND_MILLIS = 1000;
      • 这里有详细的link
      【解决方案9】:

      步骤 1. 将您的时间字符串转换为 long 类型的毫秒格式

      第 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!

      【讨论】:

      • 这是否考虑了夏令时?
      • 你没有提供getCurrentTime()的方法。
      【解决方案10】:

      您可以在 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;
      }
      

      【讨论】:

        【解决方案11】:
        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;
        
          }
        
        }
        

        【讨论】:

        • 您能否对此提供更清晰的说明。如果您需要帮助,可以检查一下吗stackoverflow.com/help/mcve.
        • 感谢这个fam,我翻译并修改了你的代码希望你不介意?
        【解决方案12】:

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

        /*
        * 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";
            }
        }
        

        谢谢

        【讨论】:

          【解决方案13】:

          请检查下面的代码,以模块化和可重用的方式完美地做到这一点,这也会像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();
                      }
                  }
          
              }
          }
          

          【讨论】:

            【解决方案14】:

            您要转换的是符合ISO 8601 的格式。最简单的转换方法是在 Android 上使用 Joda-Time library

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

                DateTimeZone timeZone = DateTimeZone.getDefault();
                DateTimeFormatter formatter = DateTimeFormat.forPattern("dd MMMM yyyy").withZone(timeZone);
                DateTime dateTime2 = new DateTime( isoDateToBeConverted, timeZone );
                String output = formatter.print( dateTime2 );
                Log.w("TIME IF WORKS::",""+output);
            

            另外,请参阅 this 以按照您的首选设置日期格式 希望对您有所帮助!

            【讨论】:

            • 如果有帮助,请将其标记为答案!
            • 什么是 isoDateToBeConverted ? @shaheen
            • 2016-01-24T16:00:00.000Z 这样的日期
            • 这个答案完全错过了问题的“时间前”部分,Joda-Time 的设计并不好。
            • 没想到spoonfeeding 最困难的部分是将其从ISO格式更改为正确的日期格式,切换到时间前只需要额外的几行代码!
            【解决方案15】:

            修改以上答案:

            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;
               }
            
            }
            

            【讨论】:

              【解决方案16】:

              当我浏览所有答案时,有很多方法可以获得此查询的解决方案,无论如何,以下答案不需要任何第三方模块或任何本机 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

              【讨论】:

                【解决方案17】:

                java.time

                java.util 日期时间 API 及其格式化 API SimpleDateFormat 已过时且容易出错。建议完全停止使用,改用modern Date-Time API*

                另外,下面引用的是来自home page of Joda-Time的通知:

                请注意,从 Java SE 8 开始,用户被要求迁移到 java.time (JSR-310) - JDK 的核心部分,它取代了这个项目。

                使用现代日期时间 API java.time 的解决方案:您可以使用在 Java-8 中作为 JSR-310 implementation 的一部分引入的 java.time.Duration 来型号ISO_8601#DurationJava-9 引入了一些更方便的方法。

                演示:

                import java.time.Duration;
                import java.time.Instant;
                import java.util.concurrent.TimeUnit;
                
                public class Main {
                    public static void main(String args[]) {
                        String strDateTime = "2016-01-24T16:00:00.000Z";
                        Instant then = Instant.parse(strDateTime);
                        Instant now = Instant.now();
                        Duration duration = Duration.between(then, now);
                        System.out.println(duration);
                
                        // ####################################Java-8####################################
                        String formatted = String.format("%d days %02d hours %02d minutes %02d seconds %02d milliseconds ago",
                                duration.toDays(), duration.toHours() % 24, duration.toMinutes() % 60, duration.toSeconds() % 60,
                                TimeUnit.MILLISECONDS.convert(duration.toNanos() % 1000_000_000, TimeUnit.NANOSECONDS));
                        System.out.println(formatted);
                        // ##############################################################################
                
                        // ####################################Java-9####################################
                        formatted = String.format("%d days %02d hours %02d minutes %02d seconds %02d milliseconds ago",
                                duration.toDaysPart(), duration.toHoursPart(), duration.toMinutesPart(), duration.toSecondsPart(),
                                TimeUnit.MILLISECONDS.convert(duration.toNanosPart(), TimeUnit.NANOSECONDS));
                        System.out.println(formatted);
                        // ####################################Java-9####################################
                    }
                }
                

                输出:

                PT50117H11M53.914442S
                2088 days 05 hours 11 minutes 53 seconds 914 milliseconds ago
                2088 days 05 hours 11 minutes 53 seconds 914 milliseconds ago
                

                ONLINE DEMO

                通过 Trail: Date Time 了解有关 modern Date-Time API* 的更多信息。


                * 如果您正在为一个 Android 项目工作并且您的 Android API 级别仍然不符合 Java-8,请检查 Java 8+ APIs available through desugaring。请注意,Android 8.0 Oreo 已经提供了support for java.time

                【讨论】:

                  【解决方案18】:

                  试试这个

                  我在尝试将时间戳转换为时间前格式时遇到了同样的问题(Unhandled execption java.text.ParseExecption),经过研发后终于得到了解决方案......现在这个错误已经出现了解决了

                  • 在你的 bulid.gradle(Module:app) 中添加这个(compile '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 "";
                    }
                    

                    注意它会显示

                  • 片刻之前(当前时间)

                  • 分钟前

                  • 一天前

                  【讨论】:

                    【解决方案19】:

                    为时已晚,但试试这个,

                     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;
                    }
                    

                    【讨论】:

                      【解决方案20】:

                      作为 Kotlin 扩展函数(将 App.context 替换为您自己的上下文):

                      fun Long.msToTimeAgo(): String {
                          val seconds = (System.currentTimeMillis() - this) / 1000f
                      
                          return when (true) {
                              seconds < 60 -> App.context.resources.getQuantityString(R.plurals.seconds_ago, seconds.toInt(), seconds.toInt())
                              seconds < 3600 -> {
                                  val minutes = seconds / 60f
                                  App.context.resources.getQuantityString(R.plurals.minutes_ago, minutes.toInt(), minutes.toInt())
                              }
                              seconds < 86400 -> {
                                  val hours = seconds / 3600f
                                  App.context.resources.getQuantityString(R.plurals.hours_ago, hours.toInt(), hours.toInt())
                              }
                              seconds < 604800 -> {
                                  val days = seconds / 86400f
                                  App.context.resources.getQuantityString(R.plurals.days_ago, days.toInt(), days.toInt())
                              }
                              seconds < 2_628_000 -> {
                                  val weeks = seconds / 604800f
                                  App.context.resources.getQuantityString(R.plurals.weeks_ago, weeks.toInt(), weeks.toInt())
                              }
                              seconds < 31_536_000 -> {
                                  val months = seconds / 2_628_000f
                                  App.context.resources.getQuantityString(R.plurals.months_ago, months.toInt(), months.toInt())
                              }
                              else -> {
                                  val years = seconds / 31_536_000f
                                  App.context.resources.getQuantityString(R.plurals.years_ago, years.toInt(), years.toInt())
                              }
                          }
                      }
                      

                      将以下内容添加到您的字符串资源中:

                      <plurals name="seconds_ago">
                          <item quantity="one">%d second ago</item>
                          <item quantity="other">%d seconds ago</item>
                      </plurals>
                      
                      <plurals name="minutes_ago">
                          <item quantity="one">%d minute ago</item>
                          <item quantity="other">%d minutes ago</item>
                      </plurals>
                      
                      <plurals name="hours_ago">
                          <item quantity="one">%d hour ago</item>
                          <item quantity="other">%d hours ago</item>
                      </plurals>
                      
                      <plurals name="days_ago">
                          <item quantity="one">%d day ago</item>
                          <item quantity="other">%d days ago</item>
                      </plurals>
                      
                      <plurals name="weeks_ago">
                          <item quantity="one">%d week ago</item>
                          <item quantity="other">%d weeks ago</item>
                      </plurals>
                      
                      <plurals name="months_ago">
                          <item quantity="one">%d month ago</item>
                          <item quantity="other">%d months ago</item>
                      </plurals>
                      
                      <plurals name="years_ago">
                          <item quantity="one">%d year ago</item>
                          <item quantity="other">%d years ago</item>
                      </plurals>
                      

                      【讨论】:

                        猜你喜欢
                        • 2022-12-08
                        • 1970-01-01
                        • 1970-01-01
                        • 2013-09-26
                        • 1970-01-01
                        • 1970-01-01
                        • 1970-01-01
                        • 1970-01-01
                        • 1970-01-01
                        相关资源
                        最近更新 更多