Android Developer

抢购倒计时

img img1


fun main(args: Array<String>) {
    var aaa = 8 * 60 * 60 * 1000.toLong()
    thread {
        while (true) {
            try {
                Thread.sleep(100)
            } catch (e: InterruptedException) {
                e.printStackTrace()
            }
            aaa -= 100
            val timer = getCountDownTime(aaa)
            println(timer)
        }
    }
}

private fun getCountDownTime(totalTime: Long): String {
    val actionTime: String
    val s = 1000
    val m = s * 60
    val h = m * 60
    val d = h * 24
    val day = (totalTime / d).toInt()
    val hour = (totalTime % d / h).toInt()
    val min = (totalTime % h / m).toInt()
    val second = (totalTime % m / s).toInt()
    val centimeterSecond = (totalTime % s / 100).toInt()
    actionTime = if (day > 0) {
        String.format(Locale.CHINA, "%02d天 %02d小时", day, hour)
    } else {
        String.format(Locale.CHINA, "%05d:%02d:%02d:%d", hour, min, second, centimeterSecond)
    }
    return actionTime
}

输出日志

00007:59:08:9
00007:59:08:8
00007:59:08:7
00007:59:08:6
00007:59:08:5
00007:59:08:4
00007:59:08:3
00007:59:08:2
00007:59:08:1
00007:59:08:0
00007:59:07:9
00007:59:07:8
00007:59:07:7
00007:59:07:6
00007:59:07:5
00007:59:07:4
00007:59:07:3

有一个细节的地方

可以看到日志输出的7前面有四个0,这个是使用了位数不够前面补零操作

java中int转成String位数不足前面补零

String.format(Locale.CHINA, “%05d:%02d:%02d:%d”, hour, min, second, centimeterSecond)

  • 0代表前面要补的字符

  • 5代表字符串长度

  • d表示参数为整数类型