有什么方法可以每小時和一天中的另一個時段下載嗎?我的意思是串列形式的結果。
[
"00:00", // start of the day e.q 14.03
"01:00",
"02:00",
....
"23:00",
"00:00 // end of the day e.q 14.03
]
和
[
"00:00", // start of the day e.q 14.03
"00:30",
"01:00"
"01:30"
....
"00:00 // end of the day e.q 14.03
]
和
[
"00:00", // start of the day e.q 14.03
"00:15",
"00:30"
"00:45"
"01:00"
....
"00:00 // end of the day e.q 14.03
]
當然可以手動添加它,但這不是一個特別優雅的解決方案。是否可以在不明確將常量宣告為每小時值的情況下做到這一點?最好的解決方案是不使用回圈和 if else 構造的函式。
我還沒有找到這種解決方案的實作。我自己也花了一個小時在這上面沒有成功。我需要它來實作從這樣的 eq 小時串列中創建 Map 或對串列的功能:
[
"00:00 - 01:00",
"01:00 - 02:00",
"02:00 - 03:00 "
//.......
"23:00 - 00:00"
]
有沒有人有機會實施這樣的問題并且能夠提供幫助?
uj5u.com熱心網友回復:
您可以撰寫一個函式來生成Sequence<LocalTime>這樣的:
fun generateTimesOfDay(interval: java.time.Duration) = sequence {
if (interval > java.time.Duration.ofDays(1)) {
yield(LocalTime.MIDNIGHT)
return@sequence
}
var time = LocalTime.MIDNIGHT
while (true) {
yield(time)
val newTime = time interval
if (newTime > time) {
time = newTime
} else {
break // passed or reached midnight
}
}
yield(LocalTime.MIDNIGHT) // Midnight the next day to end last period
}
然后你就擁有了所有可以使用的 LocalTimestoString()和.format()一些 DateTimeFormatter 來按照你喜歡的方式格式化它們。您可以使用zipWithNext()來創建時間范圍。
val x = generateTimesOfDay(java.time.Duration.ofMinutes(15))
println(x.toList())
println(
x.zipWithNext { a, b -> "$a - $b" }.toList()
)
請注意,我使用的是完全限定java.time.Duration的,以避免與 Kotlin 標準庫 Duration 類發生沖突。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/443734.html
上一篇:用相同值的變數號初始化串列
