-1

Hello I have this problem that I don't know how to fix. I have this piece of code in JavaScript. There are two console logs that writes variable to console that I later compare if one is bigger than other. Problem is that JavaScript wrongly compare them in if(alarmArray[i].ExtId < offsetTime) even if alarmArray[i].ExtId = 11:42:35 and offsetTime = 11:42:7 the condition is still meet and IF will return true. Is this some kind of JavaScript bug?

for (var i = alarmArray.length - 1; i >= 0; i -= 1) {
        console.log(alarmArray[i].ExtId);    //writes 11:42:37
        console.log(offsetTime);             //writes 11:42:7
        if (alarmArray[i].ExtId < offsetTime) {  
            console.log(alarmArray[i]);  
            alarmArray.splice(i, 1);
        }
    }
ilter
  • 4,030
  • 3
  • 34
  • 51
Mitre
  • 273
  • 1
  • 3
  • 11
  • 3
    Maybe if we had a clue what `alarmArray` or `offsetTime` contained we could be more helpful. – Nicholas Hazel Jun 11 '15 at 10:08
  • 1
    Well its in the text and next to that code. alarmArray[i].ExtId = 11:42:35 and offsetTime = 11:42:7 its time comparing.There are two console logs that writes those compared values. – Mitre Jun 11 '15 at 10:10
  • are those string values? if yes this is the expected behaviour.... –  Jun 11 '15 at 10:11
  • 4
    Look here: [How can I compare two time strings in the format HH:MM:SS?](http://stackoverflow.com/questions/6212305/how-can-i-compare-two-time-strings-in-the-format-hhmmss) – fatrex Jun 11 '15 at 10:11
  • Loops take time to run. You're running a loop and expecting the same time to output if I had to guess, but you're coming up fractions offset. – Nicholas Hazel Jun 11 '15 at 10:12
  • Yes those are strings but if this is expected shouldnt "11:42:35" still be bigger than "11:42:7"? – Mitre Jun 11 '15 at 10:12
  • 1
    in string comparison "11:42:3" + any char is lower than "11:42:7", you need to convert the values to date or number to make this work –  Jun 11 '15 at 10:14

2 Answers2

0

You can compare two strings directly if you use the correct format:

HH:MM:SS < HH:MM:SS

But you are trying to compare HH:MM:SS < HH:MM:S which is a wrong format.

Actually, I think the best answer is here: https://stackoverflow.com/a/6212411/3648578

Community
  • 1
  • 1
kosmos
  • 4,253
  • 1
  • 18
  • 36
0

Ok its fixed. I forgot add zero to seconds and minutes in function that formate my time.function formatTime(item) { var hour = item.getHours(), min = item.getMinutes(), sec = item.getSeconds(); if (sec <= 9) sec = "0" + sec; if (min <= 9) min = "0" + min; var time = "" + hour + ":" + min + ":" + sec + ""; return time; }

if (sec <= 9) sec = "0" + sec; if (min <= 9) min = "0" + min; was missing in my code

Mitre
  • 273
  • 1
  • 3
  • 11