提问人:Hasnain Ghias 提问时间:8/11/2020 最后编辑:Arvind Kumar AvinashHasnain Ghias 更新时间:9/16/2020 访问量:631
Android 错误“org.threeten.bp.temporal.UnsupportedTemporalTypeException:不支持的单位:秒”
Android error "org.threeten.bp.temporal.UnsupportedTemporalTypeException: Unsupported unit: Seconds"
问:
我正在使用“com.jakewharton.threetenabp:threetenabp:1.2.4”库为较低的 api 版本使用较新功能 DateTimeFormatter。
我有一种情况,我必须首先转换JSON响应中的日期,该响应采用“2020-07-23T00:00:00.000Z”格式。
然后我必须获取开始日期和结束日期之间的秒数才能启动计数器。
这是我创建的解决方案:
public static long dateFormat(String start, String end) {
DateTimeFormatter inputFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", Locale.ENGLISH);
DateTimeFormatter outputFormatter = DateTimeFormatter.ofPattern("dd-MM-yyy", Locale.ENGLISH);
LocalDate startDate = LocalDate.parse(start, inputFormatter);
LocalDate endDate = LocalDate.parse(end, inputFormatter);
String start_date = outputFormatter.format(startDate);
String end_date = outputFormatter.format(endDate);
LocalDate sDate = LocalDate.parse(start_date, outputFormatter);
LocalDate eDate = LocalDate.parse(end_date, outputFormatter);
return ChronoUnit.SECONDS.between(sDate, eDate);
}
我收到错误“org.threeten.bp.temporal.UnsupportedTemporalTypeException: Unsupported unit: Seconds”
我在适配器内调用该方法,我认为这可能会导致问题。
这是我的适配器代码:
public class ViewHolder extends BaseViewHolder {
@BindView(R.id.offer_pic)
ImageView offers_pic;
@BindView(R.id.offer_countdown)
CountdownView offer_countdown;
ViewHolder(View itemView) {
super(itemView);
ButterKnife.bind(this, itemView);
prefManager = new PrefManager(mContext);
}
public void onBind(int position) {
super.onBind(position);
Doc item = mData.get(position);
offer_title.setText(item.getTitle());
offer_short_desc.setText(item.getDescription());
Glide.with(mContext)
.asBitmap()
.load(item.getImage())
.into(offers_pic);
Log.d("diff1", ViewUtils.dateFormat(item.getStart(), item.getEnd()) + "empty");
}
}
是的,我已经在片段中初始化了它,例如 AndroidThreeTen.init(getActivity());
我是这种时间和日期格式的新手。一些帮助将不胜感激。
答:
1赞
Arvind Kumar Avinash
9/12/2020
#1
您不需要为给定的日期时间字符串创建,因为它已经采用 Instant#parse
使用的格式。此外,您不需要将解析的日期时间转换为其他类型,因为适用于任何类型。DateTimeFormatter
Instant
ChronoUnit.SECONDS.between
Temporal
import java.time.Instant;
import java.time.temporal.ChronoUnit;
public class Main {
public static void main(String[] args) {
// Test
System.out.println(secondsBetween("2020-07-23T00:00:00.000Z", "2020-07-23T00:10:20.000Z"));
}
public static long secondsBetween(String startDateTime, String endDateTime) {
return ChronoUnit.SECONDS.between(Instant.parse(startDateTime), Instant.parse(endDateTime));
}
}
输出:
620
关于您提到的例外情况的说明:您尝试从仅包含日期部分(即年、月和月中的某一天)而不包含任何时间部分(即小时、分钟、秒、纳秒等)的对象中获取。如果您尝试使用具有时间分量的类型(例如),则不会出现此异常。seconds
LocalDate
LocalDateTime
评论
LocalDate
Z