Android Countdown Timer to Date

前端 未结 7 1819
死守一世寂寞
死守一世寂寞 2020-12-14 11:34

I am trying to make a countdown timer for a game/date in android. I want to create a timer that displays the days, hours, minutes, and seconds to a date I specify with a fin

相关标签:
7条回答
  • 2020-12-14 12:19

    This is an example in kotlin also

    fun printDifferenceDateForHours() {
    
            val currentTime = Calendar.getInstance().time
            val endDateDay = "03/02/2020 21:00:00"
            val format1 = SimpleDateFormat("dd/MM/yyyy hh:mm:ss",Locale.getDefault())
            val endDate = format1.parse(endDateDay)
    
            //milliseconds
            var different = endDate.time - currentTime.time
            countDownTimer = object : CountDownTimer(different, 1000) {
    
                override fun onTick(millisUntilFinished: Long) {
                    var diff = millisUntilFinished
                    val secondsInMilli: Long = 1000
                    val minutesInMilli = secondsInMilli * 60
                    val hoursInMilli = minutesInMilli * 60
                    val daysInMilli = hoursInMilli * 24
    
                    val elapsedDays = diff / daysInMilli
                    diff %= daysInMilli
    
                    val elapsedHours = diff / hoursInMilli
                    diff %= hoursInMilli
    
                    val elapsedMinutes = diff / minutesInMilli
                    diff %= minutesInMilli
    
                    val elapsedSeconds = diff / secondsInMilli
    
                    txt_timeleft.text = "$elapsedDays days $elapsedHours hs $elapsedMinutes min $elapsedSeconds sec"
                }
    
                override fun onFinish() {
                    txt_timeleft.text = "done!"
                }
            }.start()
        }
    
    0 讨论(0)
提交回复
热议问题