如何格式化从String到kotlin的日期?
我试图用SimpleDateFormat解析它,但是当我试图解析String时,它总是抛出一个异常,称为Unparseable date: "21 Agt 2022"。
这是我的代码:
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()我的应用程序运行在API 21上,所以不能使用java.time.LocalDate。
发布于 2022-08-01 11:36:35
您可以使用java.time及其LocalDate,到目前为止有两个选项:
java.time功能可用的库,您必须导入它错误的原因是缺少Locale,这也是java.time中的一个问题:
8月的缩写Agt只在两个Locale中使用:印度尼西亚(至少从你的个人资料页面来看,你似乎来自那里)和凯尼亚。
这意味着您可以使用您的代码,您只需应用印度尼西亚Locale
fun main(args: Array<String>) {
// prepare the locale your input was created in
val indonesia = Locale.forLanguageTag("id-ID")
// use it in your SimpleDateFormat
var spf = SimpleDateFormat("dd MMM yyyy", indonesia)
// parse the value
val newDate = spf.parse("21 Agt 2022")
// print the value
println(newDate)
}输出:
Sun Aug 21 00:00:00 CEST 2022这将创建一个java.util.Date,它实际上是多于月份、月份和年份的…。它也有一天的时间,但您的输入String不包含任何内容。这意味着它很有可能会在一天开始的时候增加一个。
更好/更新/仅限日期:java.time
fun main(args: Array<String>) {
// your input String
val input = "21 Agt 2022"
// prepare the locale your input uses
val indonesia = Locale.forLanguageTag("id-ID")
// prepare a DateTimeFormatter that considers Indonesian months
val dtf = DateTimeFormatter.ofPattern("dd MMM uuuu", indonesia)
// parse the String using the DateTimeFormatter
val localDate = LocalDate.parse(input, dtf)
// print the result
println(localDate)
}输出:
2022-08-21https://stackoverflow.com/questions/73192482
复制相似问题