我想以這種格式決議這個日期 2021-11-03T14:09:31.135Z ( message.created_at)
我的代碼是這樣的:
val dateFormat = SimpleDateFormat("yyyy-MM-dd hh:mm:ss.SSS")
var convertedDate = Date()
try {
convertedDate = dateFormat.parse(message.created_at)
} catch (e: ParseException) {
e.printStackTrace()
}
決議失敗
uj5u.com熱心網友回復:
不要使用SimpleDateFormat它已經過時和麻煩。
使用DateTimeFormatter決議日期。
fun parseDate() {
var formatter: DateTimeFormatter? = null
val date = "2021-11-03T14:09:31.135Z" // your date string
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'") // formatter
val dateTime: LocalDateTime = LocalDateTime.parse(date, formatter) // date object
val formatter2: DateTimeFormatter =
DateTimeFormatter.ofPattern("EEEE, MMM d : HH:mm") // if you want to convert it any other format
Log.e("Date", "" dateTime.format(formatter2))
}
}
輸出: 11 月 3 日,星期三:14:09
要在 android 8 下使用它,請使用desugaring
uj5u.com熱心網友回復:
好吧,格式不完全是字串的樣子:
- 你有一個空格而不是
T日期和時間之間的文字 - 最后沒有偏移表示法
- 您正在使用
hh,這是 12 小時格式。使用HH來代替。
這種格式應該這樣做:
yyyy-MM-dd'T'HH:mm:ss.SSSX
但是,請注意Date和SimpleDateFormat已過時且麻煩。使用java.time來代替。如果您的 Android API 級別似乎太低,您可以使用ThreeTen Backport。
uj5u.com熱心網友回復:
如果你的最低 API 級別是 21,你可以使用API Desugaring,在這里找到一些很好的解釋。
啟用 API Desugaring 后,您可以直接將 ISO 決議String為OffsetDateTime:
val convertedDate = OffsetDateTime.parse(message.created_at)
uj5u.com熱心網友回復:
嘗試一下
fun main() {
val dateFormat = SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ss.SSS")
var convertedDate = Date()
try {
convertedDate = dateFormat.parse("2021-11-03T14:09:31.135Z")
println(convertedDate)
} catch (e: ParseException) {
e.printStackTrace()
}
}
uj5u.com熱心網友回復:
您剛剛錯過了日期格式字串中的“T”。使用此解決方案進行日期決議。
fun formatDate(inputDate: String) {
var convertedDate = Date()
val dateFormat = SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ss.SSSZ", Locale.getDefault())
try {
convertedDate = dateFormat.parse(inputDate)
print("Parsed date $convertedDate")
} catch (ignored: ParseException) {
}
//if you wish to change the parsed date into another formatted date
val dfOutput = SimpleDateFormat("dd-MMM-yyyy", Locale.getDefault())
val str :String = dfOutput.format(convertedDate)
print("Formatted date $str")
}
只需將您的“message.created_at”作為輸入引數傳遞。有關更多日期時間格式,請查看 Android 開發者網站的官方檔案。 簡單日期格式 | Android 開發人員您將在這里獲得所有可能的日期格式。
干杯..!
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/362354.html
