-1

I have a bunch of timestamps that have the following format: Year:Month:Day:Hour:Minute:Second, for example, 2017:01:01:23:59:59. All domains are zero-padded decimal numbers.

I am trying to write a function to determine if a given timestamp is within a range:


function isBetween(start, end, toCompare) {
}

for example, isBetween('2017:01:01:23:59:58', "2017:01:02:23:59:58", "2017:01:01:23:59:59") should return true as "2017:01:01:23:59:59" is between '2017:01:01:23:59:58' and "2017:01:02:23:59:58"

I couldn't find a clean way to do it. Can someone help me with this?

Joji
  • 4,703
  • 7
  • 41
  • 86
  • 2
    Have you tried anything? A first step would be to split your problem in two: parsing a timestamp into a number or Date (using RegExp or str.split), then doing the comparison. – Domino Sep 16 '22 at 17:04
  • I would reformat your strings into `YYYY-MM-DDTHH:mm:ss` pattern, create Date objects and use built-in comparisons. – PM 77-1 Sep 16 '22 at 17:11
  • what is the built-in comparison you were referring to? @PM77-1 – Joji Sep 16 '22 at 17:13
  • https://stackoverflow.com/questions/492994/compare-two-dates-with-javascript – PM 77-1 Sep 16 '22 at 17:15

2 Answers2

1

In JavaScript, Date objects can be compared fairly easily. However, as you've probably noticed, the format of the string you provided is not a format that can be parsed by JavaScript's Date object, so we will first have to fix that. Fortunately, this format is extremely predictable.

The first thing I notice is that the "Month" and "Date" are preceded by a zero if they're a single digit. This means that the date portion is always the exact same amount of characters (10). Because this is the case, we can use String.prototype.substring() to get the first 10 characters for the date, and get everything after the 11th character to get the time while skipping the colon in the middle.

var datetime = "2017:01:01:23:59:58";

var date = datetime.substring(0, 10);
var time = datetime.substring(11);

console.log("Date: " + date);
console.log("Time: " + time);

Now that they're separate, all we need to do is replace the colons in the date with forward slashes, then concatenate it with the time separated by a space. After this, we will have a date string in the MM/dd/yyyy hh:mm:ss format, which we can then parse using JavaScript's built in Date class.

var input = "2017:01:01:23:59:58";

var date = input.substring(0, 10).replace(/:/g, "/");
var time = input.substring(11);

var datetime = date + " " + time;
console.log(new Date(datetime));

Now we can throw this into it's own function, then use simple comparison to figure out if toCompare is between start and end.

function isBetween(start, end, toCompare) {
  var startDate = convertDate(start);
  var endDate = convertDate(end);
  var compareDate = convertDate(toCompare);

  return compareDate > startDate &&
         compareDate < endDate
}

function convertDate(input){
  var date = input.substring(0, 10).replace(/:/g, "/");
  var time = input.substring(11);
  var datetime = date + " " + time;
  
  return new Date(datetime);
}

var between = isBetween("2017:01:01:23:59:58", "2017:01:02:23:59:58", "2017:01:01:23:59:59");
console.log(between)
Jesse
  • 1,386
  • 3
  • 9
  • 23
  • so you can compare two `Date` objects directly with `<`/`>`/`==`? – Joji Sep 16 '22 at 18:28
  • `<`, `<=`, `>=` and `>` yes, `==` not exactly. Angle bracket comparisons are purely mathematical, but equality comparisons check for object equality not mathematical equality (unless the provided object is a number). [Here](https://stackoverflow.com/a/493018/10601203) is an answer that goes a bit more in-depth on that. – Jesse Sep 16 '22 at 18:35
  • Correction: unless the provided object is a value type (such as a number or a string) as opposed to a reference type which objects are. – Jesse Sep 16 '22 at 18:43
0

This could work for you:

function isBetween(start, end, toCompare) {
    start = dateGenerator(start)
    end = dateGenerator(end)
    toCompare = dateGenerator(toCompare)

    if(start <= toCompare && toCompare <= end) return true
    return false
}

function dateGenerator(str) {
    str = str.split(":")
    let date = new Date(`${str[0]}-${str[1]}-${str[2]}`)
    date.setHours(str[3],str[4],str[5])
    return date.valueOf()
}

const truthy = isBetween('2017:01:01:23:59:58', "2017:01:02:23:59:58", "2017:01:01:23:59:59")

console.log(truthy)

Firstly get individual values and add accordingly to Date constructor of JS and set the hours accordingly. For comparison we can convert this unix figures (valueOf), hence it will be easier to compare. This may seem as complex approach but it works.