0

我从服务器响应中以字符串形式获取时间戳,例如..

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"它应该让我返回真实。

我已将StringtoDate然后转换为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
    }
}

但这似乎没有按预期工作。请帮忙。谢谢..

4

1 回答 1

1

我会通过以下方式做到这一点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))
}
于 2021-07-06T11:57:06.317 回答