我使用Preference-Tree来设置值。这是我的代码
fun getWorkingHours(): Map<String, String> {
val branches = libraryBranchesLiveData.value!!
val hoursByDay : MutableMap<String, String> = mutableMapOf()
val daysOfWeek = listOf("Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat")
if (branches[selectedBranchIdPositionInList].opened_time?.isEmpty() == true) {
for (day in daysOfWeek) {
hoursByDay[day] = "Closed"
}
return hoursByDay
}
for (day in daysOfWeek) {
val hoursForDay = StringBuilder()
var startHour : String? = ""
for (workingHour in branches[selectedBranchIdPositionInList].opened_time!!) {
Log.e("working hours: ", "workingHour:${workingHour}")
val parts = workingHour!!.split(":", limit = 2)
val dayRange = parts[0]
val hours = parts[1]
Log.e("working hours: ", "dayRange${dayRange}")
Log.e("working hours: ", "hours${hours}")
if (day in dayRange) {
if (hoursForDay.isNotEmpty()) {
hoursForDay.append(", ")
}
hoursForDay.append(hours)
}
}
if (hoursForDay.isNotEmpty()) {
hoursByDay[day] = "$hoursForDay"
} else {
hoursByDay[day] = "Closed"
}
Log.e("working hours: ", "${hoursByDay}")
}
return hoursByDay
}
然后在这里调用它并设置值
findPreference<Preference>(getString(R.string.branch_info_monday_opening_time_preference_key))?.summary = branchDetailsViewModel.getWorkingHours()["Mon"]
但是它给予的这个函数是错误的这个函数的输出是
如果"opened_time": ["Sun - Thu:8:00 am-8:00 pm","Fri:8:00 am-12:00 pm"]
,则:
Sun = 8:00 am-8:00 pm
Mon = Closed
Tue = Closed
Wed = Closed
Thu = 8:00 am-8:00 pm
Fri = 8:00 am-12:00 pm
我需要做一个函数,将日期和时间从一个数组中分离出来,这个数组是我从API中得到的,比如"opened_time": ["Sun - Thu:8:00 am-8:00 pm","Fri:8:00 am-12:00 pm"]
。我想做一个函数来设置它在DayofWeek的行为,像这样:
Sun = 8:00 am-8:00 pm
Mon = 8:00 am-8:00 pm
Tue = 8:00 am-8:00 pm
Wed = 8:00 am-8:00 pm
Thu = 8:00 am-8:00 pm
Fri = 8:00 am-12:00 pm
// and Saturday it will be like this
Sat = Closed
1条答案
按热度按时间hmmo2u0o1#
你实际上并没有检查任何范围,你只是检查字符串
day
是否存在于字符串dayRange
中。Monday 在 Sunday to Thursday 范围内,但"Mon"
不在文本"Sun - Thu"
中。您需要一些逻辑来将其实际解析为一个日期范围,然后检查目标日期是否福尔斯该范围内。这有点棘手,因为范围是圆形的。一个快速的方法是这样的:
需要注意的一件事是,如果
indexOf
在列表中找不到匹配项,则会得到-1
,这将始终使target <= end
* 为true*。你可以用不同的方式来做(比如检查target in 0..start || target in end..daysOfWeek.lastIndex
),但理想情况下,这永远不会发生,因为你应该早点验证这些字符串,只有当它们在列表中时才在这里检查它们。您可以添加一行代码,如assert(listOf(start, end, target).all { it > -1 })
,以清楚地表明此函数期望处理它,并且它是需要处理的东西