我有一個采用這種格式的日期:2027-02-14T14:20:00.000
在這種情況下,我想花幾個小時和幾分鐘:14:20
我試圖做這樣的事情:
val firstDate = SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.US).parse("2027-02-14T14:20:00.000")
val firstTime = SimpleDateFormat("H:mm").format(firstDate)
但我崩潰了 java.text.ParseException: Unparseable date
如何從該字串中獲取小時和分鐘?
uj5u.com熱心網友回復:
推薦方式之一
如果您可以使用java.time,這里有一個注釋示例:
import java.time.LocalDateTime
import java.time.LocalDate
import java.time.format.DateTimeFormatter
fun main() {
// example String
val input = "2027-02-14T14:20:00.000"
// directly parse it to a LocalDateTime
val localDateTime = LocalDateTime.parse(input)
// print the (intermediate!) result
println(localDateTime.format(DateTimeFormatter.ISO_LOCAL_DATE_TIME))
// then extract the date part
val localDate = localDateTime.toLocalDate()
// print that
println(localDate)
}
這會輸出 2 個值,中間LocalDateTime決議和提取LocalDate(后者只是toString()隱式呼叫其方法):
2027-02-14T14:20:00
2027-02-14
不推薦,但仍有可能:
仍然使用過時的 API(當涉及大量遺留代碼時可能需要,我懷疑你會發現這些代碼是用 Kotlin 撰寫的):
import java.text.SimpleDateFormat
fun main() {
val firstDate = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS")
.parse("2027-02-14T14:20:00.000")
val firstTime = SimpleDateFormat("yyyy-MM-dd").format(firstDate)
println(firstTime)
}
輸出:
2027-02-14
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/476541.html
