如何在kotlin中以所需的方式重新格式化日期?



我有这种响应2023-04-04 21:00:00,但我需要向用户显示这种文本04/04 21:00。是否有一种简单的方法来重新格式化原始日期,以简化Kotlin的最终结果?

您可以使用SimpleDateFormatter来解析和格式化字符串中的日期。

From the docs:

SimpleDateFormat是一个具体的类,用于以语言环境敏感的方式格式化和解析日期。它允许格式化(date ->文本),解析(Text ->日期),并进行规范化。

下面是一个关于如何使用它来匹配您的用例的示例:

// We will use this instance to parse a string into a date
val inputDateFormatter = SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault())
// We'll use this one to format the date into the desired string
val outputDateFormatter = SimpleDateFormat("MM/dd HH:mm", Locale.getDefault())val parsedDate = inputDateFormatter.parse("2023-04-04 21:00:00")
val parsedDate = inputDateFormatter.parse("2023-04-04 21:00:00")
val formattedDateString = outputDateFormatter.format(parsedDate)

注意我正在使用Locale。getDefault解析日期,但如果需要,可以更改为使用另一个区域设置

最新更新