最好的方法是什么。我使用了两个不同的API,一个以字符串形式返回日期,另一个以Int时间戳形式返回日期(例如162000360 (
我在日期/时间类中使用ThreeTen后台端口。我已经成功地为我以字符串形式返回的日期创建了一个类型转换器-在下面提供
@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需要一个String传入其中,并且不允许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()
}
}
可能有点过时,但希望它能正常工作
您可能正在寻找ofInstant
:
fun intToDate(int: Int?) = int?.let {
LocalDate.ofInstant(Instant.ofEpochMilli(it.toLong()), ZoneId.systemDefault())
}
println(intToDate(162000360)) // 1970-01-02
此外,您可能应该使用Long
,而不是使用Int
。