获取一天中的时间段(小时/半小时/刻钟)
Get time period ( hour / half-hour / quarter hour ) of day
有什么方法可以每小时和一天中的另一个时段下载吗?
我的意思是列表形式的结果。
[
"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
]
为了示例,14.03 表示 3 月 14 日。
当然可以手动添加,但这不是一个特别优雅的解决方案。是否可以在不将常量显式声明为每小时值的情况下执行此操作?
最好的解决方案是不使用循环和 if else 构造的函数。
我还没有找到这种解决方案的实现。我自己也花了一个小时在这上面但没有成功。我需要它来实现从这样的 e.q 小时的列表中创建映射或对列表的功能:
[
"00:00 - 01:00",
"01:00 - 02:00",
"02:00 - 03:00 "
//.......
"23:00 - 00:00"
]
有没有人有机会实施这样的问题并且能够提供帮助?
您可以编写一个函数来生成 Sequence<LocalTime>
,如下所示:
fun generateTimesOfDay(interval: java.time.Duration) = sequence {
if (interval > java.time.Duration.ofDays(1)) {
repeat(2) { 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
}
然后你就拥有了所有可以与 toString()
或 .format()
一起使用的 LocalTimes 和一些 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 class.
发生冲突
有什么方法可以每小时和一天中的另一个时段下载吗? 我的意思是列表形式的结果。
[
"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
]
为了示例,14.03 表示 3 月 14 日。
当然可以手动添加,但这不是一个特别优雅的解决方案。是否可以在不将常量显式声明为每小时值的情况下执行此操作? 最好的解决方案是不使用循环和 if else 构造的函数。
我还没有找到这种解决方案的实现。我自己也花了一个小时在这上面但没有成功。我需要它来实现从这样的 e.q 小时的列表中创建映射或对列表的功能:
[
"00:00 - 01:00",
"01:00 - 02:00",
"02:00 - 03:00 "
//.......
"23:00 - 00:00"
]
有没有人有机会实施这样的问题并且能够提供帮助?
您可以编写一个函数来生成 Sequence<LocalTime>
,如下所示:
fun generateTimesOfDay(interval: java.time.Duration) = sequence {
if (interval > java.time.Duration.ofDays(1)) {
repeat(2) { 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
}
然后你就拥有了所有可以与 toString()
或 .format()
一起使用的 LocalTimes 和一些 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 class.