val timestampAsDateString = "25-10-2021"
val format = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")
val date = LocalDate.parse(timestampAsDateString, format)
Log.d("parseTesting","Date : ${date}")
我在此示例代碼的第三行收到以下錯誤:
W/System.err: java.time.format.DateTimeParseException:
Text '2019-12-22' could not be parsed at index 5
uj5u.com熱心網友回復:
您有一個String包含該值的輸入,"25-10-2021"但您正在嘗試使用DateTimeFormatter期望的值來決議它
- 年份是第一位和 4 位數字,您的輸入在那里有一個 2 位數字的月份日期
- 第二個連字符之后的月份的兩位數日,您的輸入在那里有四位數的年份
- 一天中的某個時間,您的輸入根本沒有
這就是為什么我建議通過以下方式更正模式
- 交換月份中的 2 位數日期和 4 位數年份(
u如果您不關心時代,請使用)和 - 離開一天中的時間,因為它會干擾決議,您無法決議不存在的內容,但是您可以在決議存在的內容后附加這些值
下面是一個例子:
fun main(args: Array<String>) {
// example input
val timestampAsDateString = "25-10-2021"
// define a formatter whose pattern matches the input format
val inputDtf = DateTimeFormatter.ofPattern("dd-MM-uuuu")
// then parse the input using the formatter
val parsedDate = LocalDate.parse(timestampAsDateString, inputDtf)
// print the toString() fun of LocalDate implicitly (ISO standard)
println("Just parsed the value $parsedDate")
// if you need a time of day, you could create a LocalDateTime:
val dateAndTime = LocalDateTime.of(parsedDate, LocalTime.MIN)
// define a formatter for the output (a built-in one here)
val outputDtf = DateTimeFormatter.ISO_LOCAL_DATE_TIME
// print the datetime using the formatter
println("Added the minimum time of day possible, now it's ${dateAndTime.format(outputDtf)}")
}
這段代碼輸出:
Just parsed the value 2021-10-25
Added the minimum time of day possible, now it's 2021-10-25T00:00:00
uj5u.com熱心網友回復:
LocalDate 不能被格式化為日期時間。所以你首先需要一個 LocalDateTime。
你可以做這樣的事情。
val timestampAsDateString = "25-10-2021"
val dateFormat = DateTimeFormatter.ofPattern("dd-MM-yyyy")
val dateTimeFormat = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")
val date = LocalDate.parse(timestampAsDateString, dateFormat)
LocalDateTime(date, LocalTime.MIN).format(dateTimeFormat)
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/365750.html
