android - 如何在 Kotlin 中转换时间戳

标签 android kotlin

我正在尝试转换来自数据 json url 的时间戳

TimeFlight.text = list[position].TimeFlight.getDateTime(toString())

我在我的应用中使用 ListView

override fun getView(position: Int, convertView: View?, parent: ViewGroup?): View {

    val view : View = LayoutInflater.from(context).inflate(R.layout.row_layout,parent,false)


    val TimeFlight = view.findViewById(R.id.time_id) as AppCompatTextView
    val LogoAriline = view.findViewById(R.id.logo_image) as ImageView

    status.text= list[position].Stauts
    TimeFlight.text = list[position].TimeFlight.getDateTime(toString())
    Picasso.get().load(Uri.parse("https://www.xxxxxxxxx.com/static/images/data/operators/"+status.text.toString()+"_logo0.png"))
        .into(LogoAriline)



    return view as View
}

private fun getDateTime(s: String): String? {
    try {
        val sdf = SimpleDateFormat("MM/dd/yyyy")
        val netDate = Date(Long.parseLong(s))
        return sdf.format(netDate)
    } catch (e: Exception) {
        return e.toString()
    }
}

json 的数据类

data class FlightShdu (val Airline : String ,val TimeFlight : String)

我使用了那个代码 getDateTime 但格式未知

see result image

最佳答案

假设 TimeFlight 是一个字符串化的纪元时间戳(以毫秒为单位),您应该将其传递给您的 getDateTime() 函数:

TimeFlight.text = getDateTime(list[position].TimeFlight)

(如果它们不是毫秒而是秒,则在将它们传递给 Date 构造函数之前简单地将它们乘以 1000)

附带说明,根据具体的用例,创建一个新的 SimpleDateFormat 对象可能不是每次调用 getDateTime() 都需要的,您可以将其设为实例变量。

此外,我建议您查看(并关注)Java naming conventions适用于 Java 和 Kotlin 应用程序。

关于android - 如何在 Kotlin 中转换时间戳,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53221044/

相关文章:

Android 设备监视器 - 提供 Android SDK 路径

android - 无法构建 osmdroid 存储库

android - 使用android sdk而不是Share Intent在Google Plus上分享照片

android - 尝试访问继承字段时出现 NullPointerException

android - 使用 ArrayIndexOutOfBoundsException 将 TextView 文本设置为静态文本崩溃(很少)

android - 从android中的上下文获取 Activity

java - kotlin 中的静态最终字段继承

kotlin - 作为启动上下文提供时 CoroutineExceptionHandler 不执行

kotlin - 如何分解对象并将其简洁地添加到列表中?

java - 使用 onClickListener 将数据发送到下一个 Activity 的一些问题