0

解决此问题的最佳方法是什么。我正在使用 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()
    }
}

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

4

1 回答 1

0

您可能正在寻找ofInstant

fun intToDate(int: Int?) = int?.let {
    LocalDate.ofInstant(Instant.ofEpochMilli(it.toLong()), ZoneId.systemDefault())
}

println(intToDate(162000360)) // 1970-01-02

此外,Int您可能应该使用 . 而不是使用Long.

于 2021-05-10T13:51:50.430 回答