【问题标题】:How to convert date String from JSON to time span如何将日期字符串从 JSON 转换为时间跨度
【发布时间】:2019-04-29 02:23:29
【问题描述】:

我从 JSON 响应中获得的时间值是 "sun dd/mm/yyyy - HH:mm" 格式,我想将其转换为时间跨度(10 分钟前,2 天前......)。为此,我做了一个方法,将给定的 dataTimeFormant 字符串转换为“X Hours Ago”格式并以字符串格式返回x hours ago,然后我可以放入 textView。

我认为一切似乎都是正确的,但是应用程序在我的代码行中以 NullPonterException 开始崩溃,所以可能我做错了。

   @RequiresApi(api = Build.VERSION_CODES.N)
public String dateConverter(String dateStringFormat) {
    Date date = null;
    SimpleDateFormat currentDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ss'Z");
    try {
        date = currentDateFormat.parse(dateStringFormat);
    } catch (ParseException e) {
        e.printStackTrace();
    }

    SimpleDateFormat requireDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    String currentDate = requireDateFormat.format(date);

    long currentTimeInMilis = 0;

    try {
        Date currentDateObject = requireDateFormat.parse(currentDate);
        currentTimeInMilis = currentDateObject.getTime();
    } catch (ParseException e) {
        e.printStackTrace();
    }
    CharSequence timeSpanString = DateUtils.getRelativeTimeSpanString(currentTimeInMilis, System.currentTimeMillis(), DateUtils.MINUTE_IN_MILLIS);

    return timeSpanString.toString();
}

我的适配器 onBindView 方法:

    @Override
    public void onBindViewHolder(ViewHolder viewHolder, final int i) {
  //...
  //...
  //...
        DateConvert converter = new DateConvert();
        String postTime = converter.dateConverter(this.news.get(i).getCreated());
        viewHolder.articleCreatedDate.setText(postTime);

    }

logcat 错误指向:

String currentDate = requireDateFormat.format(date);

和:

String postTime = converter.dateConverter(this.post.get(i).getCreated());

我无法找到原因,因为如果我删除对该函数的调用,一切都会正常运行,可能有更好的方法来实现这一点吗?

谢谢。

【问题讨论】:

  • 您是否尝试过分解这些步骤并一次一步地检查您的陈述? this.post 是否为空? this.post.get(i) 是否为空?
  • 没有一个是空的。如果我删除对 converter.dateConverter() 的调用,则不会崩溃
  • SimpleDateFormat.parse 返回null 以防出错。您的 date 为空,因为该字符串不适合您的格式。再次检查 API。
  • 是的,就像您指出的那样,问题出在模式上。我做了一些修改,但现在我会在未来使用这种模式:EEE MM/dd/yyyy - HH:mm 取自 android 文档

标签: java android json simpledateformat


【解决方案1】:

我是新来的,希望能帮到你。

我注意到的第一件事是 'Z: 之后没有单引号

SimpleDateFormat currentDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ss'Z'");

此外,问题在于“currentDateFormat”没有描述正确的日期输入格式,导致它无法正确解析。如果输入是“sun dd/MM/yyyy - HH:mm”,那么格式应该是:

SimpleDateFormat currentDateFormat = new SimpleDateFormat("EEE MM/dd/yyyy '-' HH:mm");

或者

SimpleDateFormat currentDateFormat = new SimpleDateFormat("EEE MM/dd/yyyy - HH:mm");

那么date = currentDateFormat.parse(dateStringFormat);应该能够正确解析,并且“日期”不会有“空”值。

希望这会有所帮助。

【讨论】:

  • 感谢您的回答。我已经进行了修改,但结果是在未来。今天是 2021 年 4 月 4 日。请参阅我的问题下的 cmets
  • 哦,刚刚发现我(再次)提供了错误的模式,需要"EE dd/MM/yyyy - HH:mm"
  • 日期格式只是“翻译”作为输入的内容。所以应该要么是输入是未来本身,要么是格式错误。很高兴你解决了它:)
  • 感谢您的帮助。我很感激。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-06-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多