After I retrieve the date of data field from Firestore's Timestamp. I want to format my Timestamp date to "dd MMM yyyy, HH:mm" in my recyclerview. I tried to use DateTimeFormatter but it doesn't works.
override fun onBindViewHolder(holder: OrderListViewHolder, position: Int) {
val item = orderList[position]
orderViewModel.setOrderProduct(item.foodItem)
orderViewModel.setStatus(item.status)
val foodItem = item.foodItem?.map { it.itemName }
val date = Date(item.date!!.toDate().time)
val newDate = date.toString().substring(0, 16) date.toString().substring(29, 34)
val formatter = DateTimeFormatter.ofPattern("dd MMM yyyy, HH:mm")
val formattedDate = newDate.format(formatter)
Log.d("dates", "${formattedDate}")
holder.orderDate.text = formattedDate
holder.foodName.text = foodItem.toString().removeSurrounding("[", "]")
holder.status.text = orderViewModel.status.value.toString()
}
Currently, I only know how to use substring to design my date format. But it's not my expected. How can I set my Timestamp format?
CodePudding user response:
With this code:
val date = Date(item.date!!.toDate().time)
val newDate = date.toString().substring(0, 16) date.toString().substring(29, 34)
val formatter = DateTimeFormatter.ofPattern("dd MMM yyyy, HH:mm")
val formattedDate = newDate.format(formatter)
you are taking a date from an item, creating a Date
object, then you're adding some string manipulation. Note that toString() on a date could generate different results, based on the system preferences. This is already something you should avoid.
Then you're creating a DateTimeFormatter
and using it on the newDate
, that is a String
, so it will not do what you are expecting.
You can obtain what you want simply by using the format on the date and not on the string:
val date = Date(item.date!!.toDate().time)
val formatter = DateTimeFormatter.ofPattern("dd MMM yyyy, HH:mm")
val formattedDate = date.format(formatter)
CodePudding user response:
fun getDateString(seconds: Long, outputPattern: String): String {
try {
val dateFormat = SimpleDateFormat(outputPattern, Locale.ENGLISH)
val calendar = Calendar.getInstance()
calendar.timeInMillis = seconds * 1000
val date = calendar.time
return dateFormat.format(date)
} catch (e: Exception) {
Log.e("utils", "Date format", e)
return ""
}
}