如何在String
kotlin 中格式化日期?
我尝试用 a 解析它,SimpleDateFormat
但它总是抛出一个异常,说Unparseable date: "21 Agt 2022"
当我尝试解析String
.
这是我的代码:
var spf = SimpleDateFormat("dd MMM yyyy")
val newDate = spf.parse("21 Agt 2022") // <- always error in this line
spf = SimpleDateFormat("yyyy-MM-dd")
val result = newDate?.let { it1 -> spf.format(it1) }.toString()
Run Code Online (Sandbox Code Playgroud)
我的应用程序在 API 21 上运行,因此无法使用java.time.LocalDate
.
您可以使用java.time
and its LocalDate
,到目前为止您有两个选择:
java.time
提供大多数功能的库,您必须导入它Locale
,这将是一个问题java.time
:August的缩写Agt仅在两个地方使用:印度尼西亚(您似乎来自那里,至少从您的个人资料页面来看)和 Kenia。Locale
这意味着您可以使用您的代码,只需应用印度尼西亚语Locale
:
fun main(args: Array<String>) {\n // prepare the locale your input was created in\n val indonesia = Locale.forLanguageTag("id-ID")\n // use it in your SimpleDateFormat\n var spf = SimpleDateFormat("dd MMM yyyy", indonesia)\n // parse the value\n val newDate = spf.parse("21 Agt 2022")\n // print the value\n println(newDate)\n}\n
Run Code Online (Sandbox Code Playgroud)\n输出:
\nSun Aug 21 00:00:00 CEST 2022\n
Run Code Online (Sandbox Code Playgroud)\n这将创建一个java.util.Date
实际上超过月份、年份和年份\xe2\x80\xa6 的值,它也有一天中的时间,但您的输入String
不包含任何时间。这意味着它很可能会添加一个,即一天的开始。
java.time
fun main(args: Array<String>) {\n // your input String\n val input = "21 Agt 2022"\n // prepare the locale your input uses\n val indonesia = Locale.forLanguageTag("id-ID")\n // prepare a DateTimeFormatter that considers Indonesian months\n val dtf = DateTimeFormatter.ofPattern("dd MMM uuuu", indonesia)\n // parse the String using the DateTimeFormatter\n val localDate = LocalDate.parse(input, dtf)\n // print the result\n println(localDate)\n}\n
Run Code Online (Sandbox Code Playgroud)\n输出:
\n2022-08-21\n
Run Code Online (Sandbox Code Playgroud)\n
归档时间: |
|
查看次数: |
378 次 |
最近记录: |