我想以这种格式解析这个日期 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()
}
解析失败
不要使用SimpleDateFormat
它的长过时且麻烦 https://stackoverflow.com/questions/1969442/whats-wrong-with-java-date-time-api.
Use 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.SSSXXX") // formatter
val dateTime: ZonedDateTime = ZonedDateTime.parse(date, parser) // 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))
}
}
Output:11 月 3 日星期三:14:09
要在 android 8 下面使用它,请使用脱糖 https://developer.android.com/studio/write/java8-support
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)