volkanfil
volkanfil

Reputation: 99

Kotlin check if a variable is between two numbers

I have a current time from LocalTime.now(). I want to use this current time in check if between two double number But I can't convert the time to double

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)

    }

You can find fail here.

Upvotes: 9

Views: 13823

Answers (3)

Shahab Saalami
Shahab Saalami

Reputation: 1012

The condition is to check whether it is between two numbers

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")
      }

Upvotes: 19

cactustictacs
cactustictacs

Reputation: 19524

Honestly this LocalTime > String > Float > Double conversion seems really brittle, and I think you'd be better off creating some LocalTime instances representing the specific times you want to compare. Then you can use LocalTime#isBefore and #isAfter to do your comparisons.

There are even a few constants like LocalTime.MIDNIGHT you can use. Plus LocalTimes use a limited range of values, from MIN to MAX, so you can avoid doing comparisons like testTime < 25.00

Upvotes: 0

nPn
nPn

Reputation: 16728

I think you want to convert currentTime to a Float and then use that in your compares.

val currentTimeAsFloat = CurrentTime.toFloat()

see this String method

Upvotes: 0

Related Questions