[SOLVED] Timestamp Microservice - validating input

I’m having some confusion with this project. I can enter both a unix timestamp and a natural date on their own and get a result. I’m trying to write an if statement to determine what the input is and then give the appropriate response. I’m using moment as well.

Right now I have:

//unix
if (typeof parseInt(input) === "number") {
  return {unix: input, natural: moment.unix(input).format("MMMM D, YYYY")};
    }
//natural
else if (typeof input !== "number") {
  return {unix: moment(input).unix(), natural: moment(input, "M D YYYY").format("MMMM D, YYYY")};
}
//invalid
else {
return {unix: null, natural: null};
}

The problem is that my input variable comes as a string. When I know the input is supposed to be a number I used parseInt to convert it. But if you were to input the date as 01-01-1980 It will pick that as a unix value and not as a natural date as intended.

We (I pair programmed) did this with a regEx test:

var convertDate = Date.parse(dateValue.match(/[a-zA-Z]+|[0-9]+/g).join(" "));

like so.

This is called by:

 if (!isNaN(dateValue)) { // check if user put in a number (unix time)
       // format unix time to text
    } else if (!isNaN(convertDate)) { 
 // assumes user passes in a date (e.g. 12jan2015)
    }

Oh and I forgot to mention:

var dateValue = req.params.date;

so I think the key is to use the Date.parse function to check that it is a valid date.

1 Like

Thank you!! The missing pieces of the puzzle were Date.parse and isNan With those incorporated I have my foundations in place. From here I just have to do a bit more work on validating the different types of user input. Thanks again! :slight_smile:

1 Like