【问题标题】:How to format Firestore server timestamp in kotlin?如何在 kotlin 中格式化 Firestore 服务器时间戳?
【发布时间】:2021-12-21 12:18:27
【问题描述】:

在我从 Firestore 的时间戳中检索数据字段的日期之后。我想在我的回收站视图中将时间戳日期格式化为“dd MMM yyyy, HH:mm”。我尝试使用 DateTimeFormatter 但它不起作用。

    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()
    }

目前,我只知道如何使用子字符串来设计我的日期格式。但这不是我的预期。 如何设置时间戳格式?

【问题讨论】:

  • “它不起作用” 为什么不呢?你希望这段代码做什么?而它的作用是什么?
  • @FrankvanPuffelen 我只想格式化我的日期

标签: android firebase kotlin google-cloud-firestore


【解决方案1】:
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 ""
        }
    }

【讨论】:

    【解决方案2】:

    使用此代码:

    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)
    

    你正在从一个项目中获取一个日期,创建一个Date 对象,然后你正在添加一些字符串操作。请注意,根据系统偏好,日期上的 toString() 可能会生成不同的结果。这已经是您应该避免的事情了。 然后您将创建一个DateTimeFormatter 并在newDate 上使用它,即String,因此它不会达到您的预期。

    你可以简单地通过使用日期而不是字符串的格式来获得你想要的:

    val date = Date(item.date!!.toDate().time)
    val formatter = DateTimeFormatter.ofPattern("dd MMM yyyy, HH:mm")
    val formattedDate = date.format(formatter)
    

    【讨论】:

    • 它会从格式中得到错误信息。未解决的参考。由于接收器类型不匹配,以下候选均不适用:
    猜你喜欢
    • 2020-12-26
    • 1970-01-01
    • 2018-11-27
    • 2021-04-19
    • 1970-01-01
    • 2020-10-24
    • 2021-05-30
    • 2020-03-21
    • 1970-01-01
    相关资源
    最近更新 更多