Skip to content

Instantly share code, notes, and snippets.

@pedrohugorm
Last active December 8, 2017 19:44
Show Gist options
  • Save pedrohugorm/6f20d8bc9324a5f446630770da616e29 to your computer and use it in GitHub Desktop.
Save pedrohugorm/6f20d8bc9324a5f446630770da616e29 to your computer and use it in GitHub Desktop.
Sync Time between two devices
import kotlin.*
import kotlin.jvm.*
import java.util.*
import java.lang.*
import java.time.*
import java.time.temporal.*
/**
* We declare a package-level function main which returns Unit and takes
* an Array of strings as a parameter. Note that semicolons are optional.
*/
fun main(args: Array<String>) {
val zoneId = ZoneId.of("America/Chicago")
var serverDate = ZonedDateTime.of(2017, 12, 8, 13, 30, 0, 0, zoneId)
val nowDate = ZonedDateTime.now(zoneId)
val timeOffset: Long = -7759 //fixed for test, almost 8 seconds - 7.759s
//val timeOffset = ChronoUnit.MILLIS.between(nowDate, serverDate)
val dateTimeProvider = OffsetDateTimeProvider(timeOffset) { nowDate }
val providerNowDate = dateTimeProvider.now()
println(nowDate)
println(timeOffset)
println(providerNowDate)
println(ChronoUnit.SECONDS.between(nowDate, providerNowDate))
println(ChronoUnit.SECONDS.between(nowDate, providerNowDate) * 1000 - ChronoUnit.MILLIS.between(nowDate, providerNowDate))
}
class OffsetDateTimeProvider(val milisecondsOffset: Long, val nowFn: () -> ZonedDateTime){
fun now(): ZonedDateTime {
val nowDateTime = this.nowFn()
val result = nowDateTime.plus(milisecondsOffset, ChronoUnit.MILLIS)
return result
}
}
@pedrohugorm
Copy link
Author

Device1 fire a "Start Stopwatch event";
Device[n] obtains the time, compares with its own (in milliseconds);
Device[n] will know the time difference to sync when getting DateTimes

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment