1

Background Information

I have values representing UTC start and end times that are returned to me from a database query and stored in an array like this:

 [ '9145001323', '08:00', '12:00' ]

The second and third values in the array actually represents start time and end time respectively.

Question

I need to compare the current time in UTC format to see if it falls between the start time / end time range.

Code

This is the code I have right now to get the current date / time :

        var currentUTC = ((new Date()).toUTCString()).split(" "); //returns an array like this: [ 'Thu,', '29', 'Sep', '2016', '15:52:32', 'GMT' ]
        currentUTC[0] =currentUTC[0].substring(0, currentUTC[0].length - 1); //strip off the traling "," in the day of week name.
        currentUTC[4] =currentUTC[4].substring(0, currentUTC[4].length - 3); //strip off the seconds portion of the time

What's the best way to compare the current hour / minutes I have in my currentUTC array with the data from my database query? (let's call that array the "rules" array).

I've been reading this post Compare two dates with JavaScript

but that seems to be comparing the full date whereas I just need a hour / minute comparison.

Community
  • 1
  • 1
Happydevdays
  • 1,982
  • 5
  • 31
  • 57
  • 2
    It's possible to do it on your own, but why not use a library like moment that can handle this for you? You'll have less inconsistencies – Halfpint Sep 29 '16 at 19:00
  • See this: http://stackoverflow.com/questions/338463/how-do-i-do-a-date-comparison-in-javascript - if you do not want to write your own code. – prabodhprakash Sep 29 '16 at 19:04
  • @Alex cool. I never knew about that. I see that it works with node... I'll give it a try – Happydevdays Sep 29 '16 at 19:04
  • @Happydevdays yep, you can just include the npm package for moment and get going - their documentation is great, I'd highly recommend it! :) – Halfpint Sep 29 '16 at 19:06
  • 2
    Are you saying that the date itself doesn't matter, only the hours and minutes? If so, for each time just multiply the hours by 60, add the minutes, and compare the sums. If the date does matter, just construct Date objects for each as suggested in the duplicate question you linked to. (Moment.js is a fine library, but for a problem as simple as this one I think it's overkill.) – Daniel Beck Sep 29 '16 at 19:08
  • @DanielBeck, I like this answer too. It's simple and doesn't have external dependencies. – Happydevdays Sep 29 '16 at 19:09

1 Answers1

1

With the use of momentjs (http://momentjs.com/docs/) it could be like this:

var y = [ '9145001323', '08:00', '12:00' ]

var t1 = moment.utc(y[1], "HH:mm");
var t2 = moment.utc(y[2], "HH:mm");
var now = moment.utc();
if( now.isAfter(t1) && now.isBefore(t2) ){
   console.log(" in range ");
}
Vladimir M
  • 4,403
  • 1
  • 19
  • 24