Android中如何从ArrayList的字符串里提取日期和时间?
解决方案:从ISO时间字符串中提取日期和时间部分
嘿,这个需求很常见,我给你分享几个靠谱的实现方式,你可以根据自己的Android版本和需求来选:
方法一:简单字符串分割(快速但依赖固定格式)
因为你的时间字符串是标准ISO格式(2018-03-18T01:39:45+01:00),日期和时间用T分隔,时间和时区用+分隔,所以可以直接用字符串分割来提取:
// 从ArrayList获取完整时间字符串 String fullDateTime = allDate_time.get(0); // 提取日期部分(分割T,取第一部分) String datePart = fullDateTime.split("T")[0]; // 提取时间部分(先分割T取第二部分,再分割+取第一部分) String timePart = fullDateTime.split("T")[1].split("\\+")[0]; // 设置到TextView dateView.setText(datePart); // 假设你有一个显示时间的TextView,比如timeView TextView timeView = findViewById(R.id.timeTX); timeView.setText(timePart);
⚠️ 注意:这种方法只适合格式完全固定的情况,如果后端返回的时间格式有变化(比如T变成空格),代码就会出错。
方法二:用SimpleDateFormat(兼容低版本Android)
如果你的App需要兼容API 26以下的设备,推荐用SimpleDateFormat来解析和格式化时间,这种方式更健壮,能处理格式的细微变化:
String fullDateTime = allDate_time.get(0); // 定义输入格式,匹配ISO偏移时间格式 SimpleDateFormat inputFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX"); // 定义日期输出格式 SimpleDateFormat dateOutputFormat = new SimpleDateFormat("yyyy-MM-dd"); // 定义时间输出格式 SimpleDateFormat timeOutputFormat = new SimpleDateFormat("HH:mm:ss"); try { // 解析完整时间字符串为Date对象 Date date = inputFormat.parse(fullDateTime); // 格式化得到日期和时间字符串 String datePart = dateOutputFormat.format(date); String timePart = timeOutputFormat.format(date); // 设置到TextView dateView.setText(datePart); TextView timeView = findViewById(R.id.timeTX); timeView.setText(timePart); } catch (ParseException e) { e.printStackTrace(); // 处理解析失败的情况,比如显示默认提示 dateView.setText("日期解析失败"); }
方法三:用Java 8 DateTime API(API 26+ 推荐)
如果你的App只需要支持API 26及以上的设备,或者用了Desugar工具,推荐使用Java 8的日期时间API,它是线程安全的,比SimpleDateFormat更可靠:
String fullDateTime = allDate_time.get(0); // 使用内置的ISO偏移时间格式解析器 DateTimeFormatter inputFormatter = DateTimeFormatter.ISO_OFFSET_DATE_TIME; OffsetDateTime offsetDateTime = OffsetDateTime.parse(fullDateTime, inputFormatter); // 提取日期部分并格式化 LocalDate localDate = offsetDateTime.toLocalDate(); String datePart = localDate.format(DateTimeFormatter.ISO_LOCAL_DATE); // 提取时间部分并格式化 LocalTime localTime = offsetDateTime.toLocalTime(); String timePart = localTime.format(DateTimeFormatter.ISO_LOCAL_TIME); // 设置到TextView dateView.setText(datePart); TextView timeView = findViewById(R.id.timeTX); timeView.setText(timePart);
总结
- 如果只是快速实现且格式固定,用方法一;
- 需要兼容低版本设备,用方法二;
- 追求健壮性和现代API,用方法三。
内容的提问来源于stack exchange,提问作者Buster3650
相关产品推荐
相关产品推荐

