【问题标题】:Creating typeconvertor to convert Int timestamp to LocalDate创建类型转换器以将 Int 时间戳转换为 LocalDate
【发布时间】:2021-07-31 21:19:51
【问题描述】:

解决此问题的最佳方法是什么。我正在使用 2 个不同的 API,一个将日期作为字符串返回,另一个将日期作为 Int 时间戳返回,格式为例如162000360

我在 Date/Time 类中使用了 ThreeTen backport。我已经成功地为我作为字符串返回的日期创建了一个类型转换器 - 下面提供了

@TypeConverter
@JvmStatic
fun stringToDate(str: String?) = str?.let {
    LocalDate.parse(it, DateTimeFormatter.ISO_LOCAL_DATE)
}

@TypeConverter
@JvmStatic
fun dateToString(dateTime: LocalDate?) = dateTime?.format(DateTimeFormatter.ISO_LOCAL_DATE)

我正在努力为 Int 时间戳复制相同的内容,因为 DateTimeFormatter 需要将字符串传递给它并且不允许 Int。非常感谢任何帮助

编辑:已尝试以下实现

@TypeConverter
@JvmStatic
fun timestampToDateTime(dt : Int?) = dt?.let {
    try {
        val sdf = SimpleDateFormat("yyyy-MMM-dd HH:mm")
        val netDate = Date(dt * 1000L)
        val sdf2 = sdf.format(netDate)

        LocalDate.parse(sdf2, DateTimeFormatter.ISO_LOCAL_DATE_TIME)

    } catch (e : Exception) {
        e.toString()
    }
}

可能有点绕,但希望它可以正常工作

【问题讨论】:

    标签: java android android-studio kotlin threetenbp


    【解决方案1】:

    您可能正在寻找ofInstant

    fun intToDate(int: Int?) = int?.let {
        LocalDate.ofInstant(Instant.ofEpochMilli(it.toLong()), ZoneId.systemDefault())
    }
    
    println(intToDate(162000360)) // 1970-01-02
    

    另外,您应该使用Long,而不是使用Int

    【讨论】:

      猜你喜欢
      • 2023-03-24
      • 2019-08-11
      • 1970-01-01
      • 2021-06-03
      • 2013-02-14
      • 1970-01-01
      • 2018-01-02
      • 2012-04-30
      • 2012-08-19
      相关资源
      最近更新 更多