0

i have tried to write the following function which given a time in the future will tell me how many milliseconds until that time:

fun millisFromNow(futureTime: Long): Long {
    val now = Date(System.currentTimeMillis())
    val endDate = Date(futureTime * 1000L)
    return (endDate.time - now.time)
}

but the user can change the system clock and then currentTimeMillis will not be accurate ..... instead could i use uptimeMillis :

fun millisFromNow(futureTime: Long): Long {
        val now = Date(SystemClock.uptimeMillis())
        val endDate = Date(futureTime * 1000L)
        return (endDate.time - now.time)
    }

it seems it will work on almost all devices since 2004 on android right ? am i using it correctly in this fashion ? because currentTimeMillis is epoch time but uptimeMillis is time since last boot and assumes JVM is running. so to me this code does not make sense. ? im just using this function to start a countdownTimer so i just call it once.

update: just replacing it gives the wrong value. just system.currentTimeMillis is giving right countdown. what can i replace it with for security sake so i can get the right millisec countdown between now and a time in the future

j2emanue
  • 60,549
  • 65
  • 286
  • 456
  • Not knowing Android, I suspect that i using `uptimeMillis`, the user can reboot the device to have the counter start over. Maybe you can get a reliable time from the internet? [How to get network provided time in android programmatically](https://www.xspdf.com/resolution/58403231.html). Search for more. – Ole V.V. Feb 12 '21 at 20:10
  • that s a good idea to fetch it from the net – j2emanue Feb 13 '21 at 08:49

0 Answers0