Comparison of strings (that match the hours) in javascript is reliable? How it works?

2

It is well known that in terms of time, that 07:30 is less than 08:30 - speaking in hours.

In javascript, if we make this comparison, everything goes as expected above

'07:30' < '08:00' // true

'08:30' > '09:00' // false

But in the following case, the result is not the expected - in terms of hours, or comparison of hours.

'09:00' > '8:00' // false

Knowing that in the two examples above has nothing to do with the question of the hours, but of some internal behavior of the javascript, how is this evaluation done?

Can I trust this time comparison (since all are started with the string 0 )?

I move the question

I need to make a comparison to see if a particular property is closed or not.

So I did so

<tr class='horario'
   data-agora='<?=date('H:i:s')?>'
   data-final="18:00:00"
   data-inicial="08:00:00"
>
</tr>

var horario = $('.horario').data();

if (horario.agora >= horario.inicial && horario.agora <= horario.final) {
    $('#status').html('Aberto');
} else {
  $('#status').html('Fechado');
}
    
asked by anonymous 24.08.2015 / 19:14

1 answer

6

I think the best way is to transform the string into an object Date I find it safer than comparing strings or manipulating them for such. A very simple way is as follows:

// Verifica se hora1 é maior que hora2.
function compararHora(hora1, hora2)
{
    hora1 = hora1.split(":");
    hora2 = hora2.split(":");

    var d = new Date();
    var data1 = new Date(d.getFullYear(), d.getMonth(), d.getDate(), hora1[0], hora1[1]);
    var data2 = new Date(d.getFullYear(), d.getMonth(), d.getDate(), hora2[0], hora2[1]);

    return data1 > data2;
};

Fiddle

But a suggestion is, if you have other uses related to the date and time on your system, use momentjs .

    
24.08.2015 / 19:39