如何解决如何检查以毫秒为单位的时间是否是今天的时间并且与当前时间相差不到 10 秒?
我从服务器响应中以字符串形式获取时间戳..
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 秒的间隔内得到这个,如图所示是响应 38 秒、48 秒、58 秒...
我想检查时间戳是否是今天的,是当前时间 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
}
}
但这似乎没有按预期工作。 请帮忙。 谢谢..
解决方法
我会通过java.time
来做到这一点:
这是一个比较您的示例值的示例(并且不涉及当前时刻,该时刻位于底部):
import java.time.LocalDateTime
import java.time.ZonedDateTime
import java.time.ZoneId
import java.time.format.DateTimeFormatter
fun main() {
val isValid = isOfTodayAndNotOlderThanTenSeconds("6:7:2021 16:01:38","6:7:2021 16:01:48")
println(isValid)
}
fun isOfTodayAndNotOlderThanTenSeconds(time: String,otherTime: String) : Boolean {
// provide a formatter that parses the timestamp format
val dtf = DateTimeFormatter.ofPattern("d:M:uuuu HH:mm:ss")
// provide a time zone
val zone = ZoneId.of("UTC")
// parse the two arguments and apply the same zone to each
val other = LocalDateTime.parse(otherTime,dtf).atZone(zone)
val thatTime = LocalDateTime.parse(time,dtf).atZone(zone)
// finally return if the days/dates are equal
return thatTime.toLocalDate().equals(other.toLocalDate())
// and the first argument is at most 10 seconds older
&& !thatTime.isBefore(other.minusSeconds(10))
}
这实际上返回/打印 true
。
如果您想将其与 现在 进行比较,请调整此 fun
以仅采用一个参数并更改要比较的对象:
fun isOfTodayAndNotOlderThanTenSeconds(time: String) : Boolean {
// provide a formatter that parses the timestamp format
val dtf = DateTimeFormatter.ofPattern("d:M:uuuu HH:mm:ss")
// provide a time zone
val zone = ZoneId.of("UTC")
// take the current moment in time in the defined zone
val other = ZonedDateTime.now(zone)
// parse the argument and apply the same zone
val thatTime = LocalDateTime.parse(time,dtf).atZone(zone)
// finally return if the days/dates are equal
return thatTime.toLocalDate().equals(other.toLocalDate())
// and the argument is at most 10 seconds older
&& !thatTime.isBefore(other.minusSeconds(10))
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。