Kotlin 检查变量是否在两个数字之间

vol*_*fil 8 android kotlin

我有来自 LocalTime.now() 的当前时间。我想使用当前时间来检查两个双数之间是否存在但我无法将时间转换为双数

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    super.onViewCreated(view, savedInstanceState)

    val CurrentTime = LocalTime.now().format(DateTimeFormatter.ofPattern("HH.mm"))

    tvDetailIcon = view.findViewById(R.id.tvDetailIcon)
    testTime = view.findViewById(R.id.testTime)
    testTime.text = CurrentTime


    if (24.00<testTime && testTime<25.00 ){
        constraint.setBackgroundColor(Color.parseColor("#34495e"))
        tvDetailIcon.setImageResource(R.drawable.ic_baseline_nights_stay_24)
    }

    else if (1.00<testTime && testTime<24.00){
        constraint.setBackgroundColor(Color.parseColor("#349Bdb"))
        tvDetailIcon.setImageResource(R.drawable.ic_baseline_wb_sunny_72)

    }
Run Code Online (Sandbox Code Playgroud)

你可以在这里找到失败。

Sha*_*ami 15

条件是检查是否在两个数字之间

val number = 5
val min = 2
val max = 10

if(number in min..max){
   Log.i("Yes, number is between min and max")
   } else{
     Log.i("No, number is not between min and max")
      }
Run Code Online (Sandbox Code Playgroud)


cac*_*acs 0

老实说,这种LocalTime > String > Float > Double转换似乎非常脆弱,我认为您最好创建一些LocalTime代表您想要比较的特定时间的实例。然后您可以使用LocalTime#isBefore#isAfter进行比较。

甚至还有一些LocalTime.MIDNIGHT你可以使用的常量。PlusLocalTime使用有限范围的值,从MINMAX,因此您可以避免进行类似的比较testTime < 25.00