-3

我试图弄清楚如何将用户输入日期转换为毫秒。

这些是预期的输入类型:

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

它需要接受任一输入类型并将其转换为毫秒。或者,如果有文本,则返回 null。

这些是预期的输出:

case1: 1451001600000
case2: 1450137600
case3: null

当前代码:

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})

现场示例:

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/

工作解决方案:

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})
})
4

2 回答 2

1

我认为这很简单:

new Date("2015-12-25").getTime()
于 2018-12-14T20:16:19.310 回答
1

您需要添加代码来检测数字并相应地处理它。

  • 第一个应该在大多数引擎中使用 new Date 工作。
  • 第二个必须是数字,而不是字符串"1450137600"不等于1450137600with new Date()
  • 第三,如果两个测试失败,这意味着它一定是坏的......

所以基本代码

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")
  }
}
于 2018-12-14T22:46:38.490 回答