【发布时间】:2021-07-06 11:11:43
【问题描述】:
我从服务器响应中获取时间戳,格式为..
KS100V1C1-2C3AE8176DC1\1 {"timestamp":"3:7:2021 16:01:38","ChannelId_1":100}
KS100V1C1-2C3AE8176DC1\1 {"timestamp":"3:7:2021 16:01:48","ChannelId_1":100}
KS100V1C1-2C3AE8176DC1\1 {"timestamp":"3:7:2021 16:01:58","ChannelId_1":100}
我在 10 秒的间隙内得到这个,如图所示是响应 38sec,48sec,58sec...
我想检查时间戳是否是今天的时间,是否是当前时间 10 秒内的时间。就像时间戳是 "3:7:2021 16:01:38" 而当前时间是 "3:7:2021 16:01:48" 它应该返回 true。
我已将String 转换为Date,然后转换为Long,如下所示:
fun convertTimeToLong(time: String) : Long {
val formatter: DateFormat = SimpleDateFormat("dd:mm:yyyy hh:mm:ss")
val date = formatter.parse(time) as Date
Log.d("LongTime : ", date.time.toString())
return date.time
}
为了检查时间是否低于 10 秒,我尝试了这个:
private val TEN_SECONDS = 10 * 60 * 10000
fun isTimeUnder10Seconds(timeStamp: Long): Boolean {
val tenAgo: Long = System.currentTimeMillis() - TEN_SECONDS
if (timeStamp < tenAgo) {
Log.d("10Seconds ?"," is older than 10 seconds")
return true
} else {
Log.d("10Seconds ?"," is not older than 10 seconds")
return false
}
}
但这似乎没有按预期工作。 请帮忙。 谢谢。。
【问题讨论】:
-
我建议你不要使用
DateFormat和SimpleDateFormat。这些课程出了名的麻烦和过时。而是使用来自java.time, the modern Java date and time API 的DateTimeFormatter。查看答案。
标签: kotlin timestamp compare current-time