我从 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();
}
我的适配器在绑定视图方法:
@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);
}
日志猫错误指向:
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"值。
希望这有帮助。