1

I'd like to know if there is a javascript function that determines whether an input string is a number or a date or neither.

Here's my function and codepen:

function isNumeric(n) {
  // http://stackoverflow.com/questions/9716468/is-there-any-function-like-isnumeric-in-javascript-to-validate-numbers
  return !isNaN(parseFloat(n)) && isFinite(n);
} 
function number_or_string(i) {
  // http://stackoverflow.com/questions/7657824/count-the-number-of-integers-in-a-string
  if (i.length == 10 && i.replace(/[^0-9]/g, "").length) {
    result = 'date'
  } else if (isNumeric(i)) {
    result = 'number'
  } else {
    result = 'string'
  }
  return result
}

Is there a pre-built function that does this (or perhaps a better function, since the above function clearly has limitations)?

Mike Cluck
  • 31,869
  • 13
  • 80
  • 91
Chris
  • 5,444
  • 16
  • 63
  • 119
  • There are so many different date formats that I don't think you're going to get a simple regex solution to this problem. I would look at http://momentjs.com/ instead. – Jack Guy Oct 06 '16 at 20:41
  • you can say `var date = new Date(myString); if (date === "Invalid Date") {...}` – mhodges Oct 06 '16 at 20:41
  • For numbers, you've got your answer there [and plenty more here.](http://stackoverflow.com/questions/175739/is-there-a-built-in-way-in-javascript-to-check-if-a-string-is-a-valid-number) As for a date, it depends on the format. Is there a built-in function to handle both of these cases simultaneously? No. – Mike Cluck Oct 06 '16 at 20:41
  • Javascript has a Date.parse function https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/parse. If the value is valid then the date is returned in milliseconds otherwise NaN –  Oct 06 '16 at 20:41
  • You can use isNaN(input) to determine input is number or not – Ram Oct 06 '16 at 20:43
  • @user3698428 Should be `isNaN(Number(input))`, because the OP said it was a string – mhodges Oct 06 '16 at 20:44
  • but... even `0` can be interpreted as a date, – Kevin B Oct 06 '16 at 20:49

1 Answers1

1

Short answer: No, not really.

This is because dates can appear in several formats. You can have String dates, Date dates, or Number dates. A Unix timestamp is essentially just a 1 to 10 digit integer. You need context in order to determine what that integer represents.

However, the fact that you need a function like this in your code is indicative of a larger problem. Ideally, you should know the data types and formats of your function outputs. If you're using an API, it should have a well documented interface and thus help you avoid this problem.

But if you only need something that works 90% of the time, you could give this a try.

function isDate (x) {
  if (x instanceof Date) { return true; }

  if (typeof x === String && !isNaN(Date.parse(x))) { return true; }

  return false;
}
MDrewT
  • 66
  • 8