【问题标题】:How to use TimeAgo format with firestore or realtime database?如何将 TimeAgo 格式与 Firestore 或实时数据库一起使用?
【发布时间】:2020-09-11 06:16:07
【问题描述】:

我正在使用Github LibraryTextView 的格式显示时间,就像刚才、昨天、很久以前......等等。它显示了我想要的时间。但问题是时间并没有改变,因为它是 刚刚 在 post-it 的那一刻永远保持不变。

postAdapter的模型类

class Post {
private var date: String = ""
constructor(date: Long) {
fun getDate(): String
    {
        return date
    }

   //Initialization according to the library
    val timeInMillis = System.currentTimeMillis()
    val timeAgo = TimeAgo.using(timeInMillis)


   //saving the data to firestore
    val fStore: FirebaseFirestore = FirebaseFirestore.getInstance()
                    val post = Post(title, description, date = timeAgo)
                    fStore.collection("Posts").document()
                            .set(post)
                            .addOnSuccessListener{...}

Firestore检索数据

private fun postInfo(title: TextView, description: TextView, date: TextView) {
        val postRef = FirebaseFirestore.getInstance().collection("Posts").document()
        postRef.get()
                .addOnSuccessListener { documentSnapshot ->
                    if (documentSnapshot != null && documentSnapshot.exists()) {
                        val post = documentSnapshot.toObject(Post::class.java)
                        date.text = post?.getDate()
                        title.text = post?.getTitle()
                        description.text = post?.getDescription()
                    } 
            }
    }

【问题讨论】:

  • 显示屏幕截图以查看日期在 Firestore 中的存储方式。
  • 请更新问题检查。
  • post?.getDate() 返回什么,作为字符串的长值,对吧?
  • 是的@AlexMamo :(
  • 您似乎仍在接收 long 值。您是否尝试过可以进一步将“timeAgo”与“.ToString()”进行转换?除此之外,此日期值是否对应于 Firestore 时间戳?您是否尝试过使用任何其他库而不是这个特定的 TimeAgo?

标签: android kotlin google-cloud-firestore android-dateutils


【解决方案1】:

您所做的是使用库将日期转换为字符串,然后将 TextView 文本设置为该字符串。字符串只是字符列表,它们对它们的含义或是否需要更改/更新没有“意识”。

我建议使用来自android-agoRelativeTimeTextView。一旦您为该视图设置了参考时间,其中的一些代码会自动为您触发更新。

https://github.com/curioustechizen/android-ago

编辑:在 Firestore 中存储时,您也在进行从 timeInMillis: Longdate: String 的转换。您应该按原样存储 timeInMillis(长值),然后在读取时将其用作 relativeTimetextView.setReferenceTime(timeInMillis) 的参数。

【讨论】:

  • 我已经使用了您建议的方法,但我正在做同样的事情,所以请告诉我应该如何处理该相对布局。我的意思是在那之后我应该做什么,该视图将如何显示时间并随时间变化。
  • 您应该考虑在不进行任何转换的情况下存储timeInMillis
  • 兄弟,当我使用 long 时,它会显示一个 long 值,就像刚才 1590384536875 一样。
  • 可以分享一下使用RelativeTimeTextView的代码吗?
  • 我没有使用那个库
猜你喜欢
  • 1970-01-01
  • 2019-06-06
  • 1970-01-01
  • 2023-03-26
  • 2020-07-01
  • 2023-03-30
  • 2020-02-16
  • 2019-08-07
  • 2021-05-19
相关资源
最近更新 更多