【问题标题】:Date and time conversion日期和时间转换
【发布时间】:2018-03-05 04:35:01
【问题描述】:

我正在开发一个新闻应用程序,我从这种模式 (2017-09-23T14:22:28Z) 的 json 响应中获取日期和时间。

如何将此日期和时间转换为类似的日期和时间(5 秒前、10 分钟前、3 小时前等)? 24 小时后,它应该会显示该特定新闻标题的正常日期(2017-09-23)。

【问题讨论】:

    标签: android datetime formatting data-conversion


    【解决方案1】:

    Joda-Time 非常适合这个。

    compile 'joda-time:joda-time:2.9.9'
    


    String dateTime = "2017-09-21T14:22:28Z";
        DateTimeFormatter format = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ssZ");
        DateTime myBirthDate = format.parseDateTime(dateTime);
        DateTime now = new DateTime();
        Period period = new Period(myBirthDate, now);
        PeriodFormatter formatter = new PeriodFormatterBuilder()
                .appendSeconds().appendSuffix(" Sekonds ago\n")
                .appendMinutes().appendSuffix(" Minutes ago\n")
                .appendHours().appendSuffix(" Hours ago\n")
                .appendDays().appendSuffix(" Days ago\n")
                .appendWeeks().appendSuffix(" Weeks ago\n")
                .appendMonths().appendSuffix(" Months ago\n")
                .appendYears().appendSuffix(" Years ago\n")
                .printZeroNever()
                .toFormatter();
        if (period.getDays()<1) {
            String result = formatter.print(period);
            System.out.println(result);
        } else {
            DateTimeFormatter format24hMore = DateTimeFormat.forPattern("yyyy-MM-dd");
            String result = format24hMore.print(myBirthDate);
            System.out.println(result);
        }
    

    编辑 创建方法

    public String convertDate(String date) {
    
        String result = "";
        DateTimeFormatter format = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ssZ");
        DateTime from = format.parseDateTime(date);
        DateTime now = new DateTime();
        Period period = new Period(from, now);
        PeriodFormatter formatter = new PeriodFormatterBuilder()
                .appendSeconds().appendSuffix(" Sekonds ago\n")
                .appendMinutes().appendSuffix(" Minutes ago\n")
                .appendHours().appendSuffix(" Hours ago\n")
                .appendDays().appendSuffix(" Days ago\n")
                .appendWeeks().appendSuffix(" Weeks ago\n")
                .appendMonths().appendSuffix(" Months ago\n")
                .appendYears().appendSuffix(" Years ago\n")
                .printZeroNever()
                .toFormatter();
        if (period.getDays()<1) {
            result = formatter.print(period);
        } else {
            DateTimeFormatter format24hMore = DateTimeFormat.forPattern("yyyy-MM-dd");
            result = format24hMore.print(from);
    
        }
        return result;
    }
    

    你可以调用这个方法

    System.out.println(convertDate("2017-09-21T14:22:28Z"));
    

    【讨论】:

    • @mani 像在我所做的 EDIT 中一样应用此方法,如果响应采用这种模式“2017-09-23T14:22:28Z”,则此方法仅从您的 JSON 响应中隐藏字符串
    • 我应该在我的项目中导入哪些类??
    【解决方案2】:
    SimpleDateFormat simpledateformat = new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ss");
    Date stringDate = simpledateformat.parse(aDate, 0);
    DateUtils.getRelativeDateTimeString( this,d.getTime(), DateUtils.MINUTE_IN_MILLIS)
    

    【讨论】:

    • 就这样吗?没有别的了??
    【解决方案3】:

    您可以考虑使用 JodaTime 库来管理所有日期、时间和日历! 这是来自 Joda Time 的一些代码。

        public boolean isAfterPayDay(DateTime datetime) {
          if (datetime.getMonthOfYear() == 2) {   // February is month 2!!
          return datetime.getDayOfMonth() > 26;
       }
       return datetime.getDayOfMonth() > 28;
       }
    
       public Days daysToNewYear(LocalDate fromDate) {
           LocalDate newYear = fromDate.plusYears(1).withDayOfYear(1);
           return Days.daysBetween(fromDate, newYear);
       }
    
       public boolean isRentalOverdue(DateTime datetimeRented) {
          Period rentalPeriod = new Period().withDays(2).withHours(12);
          return datetimeRented.plus(rentalPeriod).isBeforeNow();
       }
    
       public String getBirthMonthText(LocalDate dateOfBirth) {
          return dateOfBirth.monthOfYear().getAsText(Locale.ENGLISH);
       }
    

    检查库Android SpecificJava Specific 及其文档HERE

    【讨论】:

      【解决方案4】:

      您可以使用我在聊天应用中实现的代码。

      public class Utils
      {
          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";
              }
          }
      }
      

      有很多第三方库,但您也可以参考:https://github.com/curioustechizen/android-ago

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-05-01
        • 2015-01-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多