Kotlin Android / Java 字符串日期时间格式,API21

Kotlin Android / Java String DateTime Format, API21

我想将字符串日期时间转换为格式化字符串。 例如“2018-12-14T09:55:00”到“14.12.2018 09:55”作为字符串 => Textview.text

如何使用 kotlin 或 java 为 android 执行此操作?

解析为LocalDateTime然后格式化:

LocalDateTime localDateTime = LocalDateTime.parse("2018-12-14T09:55:00");
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd.MM.yyyy HH:mm");
String output = formatter.format(localDateTime);

如果这不适用于 api21,您可以使用:

SimpleDateFormat parser = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
SimpleDateFormat formatter = new SimpleDateFormat("dd.MM.yyyy HH:mm");
String output = formatter.format(parser.parse("2018-12-14T09:55:00"));

或导入 ThreeTenABP。

Kotlin API 26 级或更高级别:

val parsedDate = LocalDateTime.parse("2018-12-14T09:55:00", DateTimeFormatter.ISO_DATE_TIME)
val formattedDate = parsedDate.format(DateTimeFormatter.ofPattern("dd.MM.yyyy HH:mm"))

低于 API 级 26:

val parser =  SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss")
val formatter = SimpleDateFormat("dd.MM.yyyy HH:mm")
val formattedDate = formatter.format(parser.parse("2018-12-14T09:55:00"))

如果您有一个表示特定时区值的日期时间,但该时区未在日期时间字符串本身中编码(例如,“2020-01-29T09:14:32.000Z”)并且您需要在您拥有的时区显示它(例如,CDT)

val parsed = ZonedDateTime.parse("2020-01-29T09:14:32.000Z", DateTimeFormatter.ISO_DATE_TIME).withZoneSameInstant(ZoneId.of("CDT"))

parsed ZoneDateTime 将反映给定的时区。例如,此日期类似于 2020 年 1 月 28 日 8:32am。

在 kotlin 中,您可以通过这种方式将字符串格式化为日期:-

val simpleDateFormat = SimpleDateFormat("yyyy/MM/dd HH:mm:ss",Locale.getDefault())
val date = SimpleDateFormat("yyyy/MM/dd", Locale.getDefault()).format(simpleDateFormat.parse("2022/02/01 14:23:05")!!)

应该导入 java.text.SimpleDateFormat 让 SimpleDateFormat Class 在 api 21

上工作