Search code examples
javascriptnode.jsdatetimegettime

Convert User Input to Milliseconds?


I'm trying to figure out how to convert a User Input date to Milliseconds.

These are the expected input types:

var case1 = "2015-12-25";
var case2 = 1450137600;
var case3 = "1450137600abcdefg";

It needs to accept either input type and convert it to milliseconds. Or if there's text it returns null.

These are the expected outputs:

case1: 1451001600000
case2: 1450137600
case3: null

Current code:

app.get('/api/timestamp/:input', function (req, res) { //User input something. Case 1, 2, and 3.
   let user_input = req.params.input;
   let new_date = new Date(user_input);
   let unix = new_date.getTime();
   let utc = new_date.toUTCString();
   res.json({"user_input": user_input, "unix": unix, "utc": utc})

Live example:

https://periodic-nightingale.glitch.me/api/timestamp/2015-12-25
https://periodic-nightingale.glitch.me/api/timestamp/1450137600
https://periodic-nightingale.glitch.me/api/timestamp/1450137600abcdefg
https://periodic-nightingale.glitch.me/

Working solution:

app.get('/api/timestamp/:input', function (req, res) { //User input something. Case 1, 2, and 3. 
  let user_input = req.params.input;

   if(!isNaN(user_input)) { //User input is a string, not a number. Case 1.
     user_input = parseInt(user_input) * 1000; 
   }

  let unix = new Date(user_input).getTime(); //Converts user_input to a Unix timestamp.
  let utc = new Date(user_input).toUTCString(); //Converts user_input to a UTC timestamp.

  res.json({"unix": unix, "utc": utc})
})

Solution

  • You need to add code to detect a number and handle it accordingly.

    • First one should work find with new Date in most engines.
    • Second one needs to be a number, not a string "1450137600" is not equivalent to 1450137600 with new Date().
    • Third, well if two tests fail, that this means it must be bad...

    So the basic code

    function foo (str) {
    
      if ((/\d{4}-\d{2}-\d{2}/).test(str)) { // if ####-##-##
        return new Date(str);
      } else if ((/^\d+$/).test(str)) {  // if #######
        return new Date(+str);  // convert string to number
      } else {
        throw new Error("Invalid format")
      }
    }