java - 如何将日期字符串从 JSON 转换为时间跨度

标签 java android json simpledateformat

我从 JSON 响应中获得的时间值的格式为 "sun dd/mm/yyyy - HH:mm" 我想将其转换为时间跨度(10 分钟前,2 分钟前)几天前...)。为此,我创建了一个方法,将给定的 dataTimeFormant 字符串转换为“X 小时前”格式,并以字符串格式返回x 小时前,然后我可以放入 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());

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

谢谢。

最佳答案

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

我注意到的第一件事是 '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); 应该能够正确解析,并且“date”不会有“null”值。

希望这有帮助。

关于java - 如何将日期字符串从 JSON 转换为时间跨度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55896241/

相关文章:

java - 将几种方法组合成唯一的一种。泛型

java - 使用地理编码器根据纬度和经度检索地址会导致延迟。安卓

android - 如何在 git 中不包含带有 API 字符串的类文件,但仍然在构建服务器上获取它?

javascript - 从 firebase 数据库中删除指定的数组

php - 将 JSON 解码为 PHP 数组时丢失了一些数据

java - 无法找到语法错​​误的原因

java - 使用 lambdaj 从嵌套数组中提取对象

Java-用鼠标绘制形状并在单击按钮后拖动

android-layout - Android 开发 - 为多种屏幕尺寸设计用户界面

javascript - 如何从 dojo.data.ItemFileReadStore 检索值