Skip to content

Instantly share code, notes, and snippets.

@wiryadev
Last active November 11, 2022 13:49
Show Gist options
  • Save wiryadev/03022d62c802caf59ed2976ddffdb4bb to your computer and use it in GitHub Desktop.
Save wiryadev/03022d62c802caf59ed2976ddffdb4bb to your computer and use it in GitHub Desktop.
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.runBlocking
import kotlinx.datetime.*
fun main(args: Array<String>) {
runBlocking {
timerPerMinute().collect {
println("collect: $it")
}
}
}
fun timerPerMinute() = flow {
val currentMillis = Clock.System.now().toEpochMilliseconds()
val nextOneMinuteDateTime = Clock.System.now().plus(1, DateTimeUnit.MINUTE)
.toLocalDateTime(TimeZone.currentSystemDefault())
val nextOneMinuteInMillis = nextOneMinuteDateTime.truncateToMinute().toEpochMilliseconds()
// subtract to find first time difference in milis for initial delay
val timeDifferenceMilis = nextOneMinuteInMillis - currentMillis
var firstTime = true
println("nextDateTimeSecond: $nextOneMinuteInMillis")
println("dateTime: $currentMillis")
println("oneMinuteLater: $timeDifferenceMilis")
while (true) {
val now = Clock.System.now()
emit(getHourAndMinute(now))
val delayAmount = if (firstTime) (timeDifferenceMilis) else 60000
println("delayAmount: $delayAmount")
firstTime = false
delay(delayAmount)
}
}
fun LocalDateTime.truncateToMinute(): LocalDateTime = LocalDateTime(
year = year,
month = month,
dayOfMonth = dayOfMonth,
hour = hour,
minute = minute,
second = 0,
)
fun LocalDateTime.toEpochMilliseconds(
timeZone: TimeZone = TimeZone.currentSystemDefault()
) = this.toInstant(timeZone).toEpochMilliseconds()
fun getHourAndMinute(
instant: Instant,
timeZone: TimeZone = TimeZone.currentSystemDefault(),
): String {
val time = instant.toLocalDateTime(timeZone).time
val hour = formatDoubleDigitTime(time.hour)
val minute = formatDoubleDigitTime(time.minute)
return "$hour:$minute"
}
private fun formatDoubleDigitTime(time: Int) = if (time > 9) time.toString() else "0$time"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment