android倒计时功能以及时间格式

2024-05-28  本文已影响0人  背锅TV丶伴奏大师
//更新时间
    private var countDownTimer: CountDownTimer?=null
    private fun startCountTime(time:Long){
        if(countDownTimer==null){
            countDownTimer = object : CountDownTimer(time, 1000) {//60*1000, 1000
                override fun onTick(millisUntilFinished: Long) {
                    val t=(millisUntilFinished/1000).toInt()//需要对数字进行取整,防止数据不准确
                    val timeSdf=getTime((t*1000).toLong())//millisUntilFinished
                   
                }
                override fun onFinish() {

                }
            }
        }
        //countDownTimer!!.cancel()
        countDownTimer!!.start()
    }
    
    private fun getTime(a: Long): String {//单位为ms
        // 总时间 中有几天
        //val day = a / (1000 * 60 * 60 * 24)
        // 总时间 去除天数后,还剩多少小时
        val hour = a  / (1000 * 60 * 60)
        // 总时间 去除天数与小时后,还剩多少分钟
        val minute = (a- hour * (1000 * 60 * 60)) / (1000 * 60)
        // 总时间 去除天数小时与分钟后,还剩多少秒
        val second = (a  - hour * (1000 * 60 * 60) - minute * (1000 * 60) )/ 1000
        var mins=minute.toString()
        var secs=second.toString()
        var hous=hour.toString()
        if(hour>0){
            if(hour<10){
                hous="0$hous"
            }
        }else{
            hous="00"
        }
        if(minute>0){
            if(minute<10){
                mins="0$mins"
            }
        }else{
            mins="00"
        }
        if(second>0){
            if(second<10){
                secs="0$secs"
            }
        }else{
            secs="00"
        }
        return "$hous:$mins:$secs"
    }
    
    override fun onDestroy() {
        countDownTimer?.cancel()
        super.onDestroy()
    }
上一篇 下一篇

猜你喜欢

热点阅读