如何在科特林转换时间戳

时间:2018-11-09 06:48:34

标签: android kotlin

我试图转换来自数据json url的时间戳

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

我在应用程序中使用列表视图

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)

l使用了该代码getDateTime,但格式未知

see result image

2 个答案:

答案 0 :(得分:2)

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

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

(如果它们不是毫秒而是秒,那么只需将它们乘以1000,然后再将它们传递给Date构造函数)

顺便说一句,根据确切的使用情况,可能不需要在每次SimpleDateFormat调用中都创建一个新的getDateTime()对象,您可以将其设为实例变量。

此外,我建议您同时关注Java和Kotlin应用程序的Java naming conventions

答案 1 :(得分:1)

这里的问题是Date构造函数自1970年1月1日以来花费的毫秒数很长,而您获得的数字是秒数。

我的建议是以下代码(您可以更改格式):

const val DayInMilliSec = 86400000

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

fun Date.addDays(numberOfDaysToAdd: Int): Date{
    return Date(this.time + numberOfDaysToAdd * DayInMilliSec)
}
相关问题