1

Time is accepted in 24hr format HH:mm

I would like to compare two ranges of times, under the following conditions:

a) T1 > T2 
b) T2 not in-between time range of T1 
c) The T1 & T2 do not overlap

Are there any libraries out there or should I just cater to all the possible combinations and create my own script?

victor
  • 1,253
  • 3
  • 15
  • 22

3 Answers3

1

There are few . check out these dateTime libraries

Amit.rk3
  • 2,417
  • 2
  • 10
  • 16
1

Your options are:

  1. A library, like momentJS.

  2. Convert the string to a standard javascript Date-Time and compare those objects instead of the strings. You need a dummy date.

  3. Roll your own, cover all the possibilities manually.

If you plan on simply making comparisons between two arrays over and over again (i.e. your JSON doesn't come in in different formats and you need more modularity in your code), I think you should just roll your own. Write a validation function with subfunctions for your three conditions, and return func1 && func1 && func3.

Also as there is a degree of 3 in all of them, especially if you have to learn a new library, I'd learn towards that. It has potential to be both the fastest and most performant for limited h:m comparison, especially as you get better with JavaScript.

Community
  • 1
  • 1
Sze-Hung Daniel Tsui
  • 2,282
  • 13
  • 20
1

I always prefer manual methods if I can, then you're in full control of what is being loaded into your page.

I suggest comparing getTime()'s, like so:

var Now = new Date(),
    T1 = {},
    T2 = {};
T1.Start = new Date(Now.getFullYear(), Now.getMonth(), Now.getDate(), 8, 30); // 8:30am
T1.End = new Date(Now.getFullYear(), Now.getMonth(), Now.getDate(), 12, 30); // 12:30pm
T2.Start = new Date(Now.getFullYear(), Now.getMonth(), Now.getDate(), 13, 0); // 1:00pm
T2.End = new Date(Now.getFullYear(), Now.getMonth(), Now.getDate(), 17, 30); // 5:30pm
T1.Length = T1.End.getTime() - T1.Start.getTime()
T2.Length = T2.End.getTime() - T2.Start.getTime()

if (T1.Length > T2.Length) { // Longer than

} else if (T2.Start > T1.Start && T2.End < T1.End) { // Inbetween

} else if (T2.Start < T1.End || T2.End > T1.Start) { // Overlapping

}
Jamie Barker
  • 8,145
  • 3
  • 29
  • 64