我从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());
我无法找到原因,因为如果我删除对该函数的调用一切正常,可能有更好的方法来实现这一点?
谢谢。
我是新来的,希望我能提供帮助。
我注意到的第一件事是'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);
应该能够正确解析,“日期”不会有“空”值。
希望这可以帮助。