我试图弄清楚如何将用户输入日期转换为毫秒。
这些是预期的输入类型:
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})
})