【发布时间】: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