Timestamp Microservice: Your project can handle dates that can be successfully parsed by `new Date(date_string)`

Tell us what’s happening:
Hi, I have only one error message before passing the test:

Your project can handle dates that can be successfully parsed by new Date(date_string)

I guess it was meant to see if I use Data.parse in my code which I have but I still get this error message. Please help me to find what I’m missing!

That’s my code so far:

app.get("/api/:date", function (req, res) {
let userInput = req.params.date;
let numberInput = Number(userInput);
let userDay = new Date(userInput);
let epoch = Date.parse(userInput);
let ud = userDay.toUTCString();

if (userInput.length > 10) { //1451001600000
let msDate = new Date(numberInput);
let humanDate = msDate.toUTCString();
if (humanDate == ‘Invalid Date’) {
res.json({error: ‘Invalid Date’});
};
res.json({“unix”: numberInput,
“utc”: humanDate});
}else if (userInput.length <= 10){ //2015-12-25
if (ud == ‘Invalid Date’) {
res.json({error: ‘Invalid Date’});
}
res.json({“unix”: epoch,
“utc”: ud});
}
});

Your project link(s)

solution: https://replit.com/@samtaitai/boilerplate-project-timestamp

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/98.0.4758.102 Safari/537.36

Challenge: Timestamp Microservice

Link to the challenge:

I think you have to try catch new Date(). If new Date cant parse the input throw error json

Thanks, but I’m afraid that I didn’t understand what you meant fully.
I tried to add Try catch statements but I’m struggling with the same error.

app.get(“/api/:date”, function (req, res) {
let userInput = req.params.date;
let userDay = new Date(userInput);
let numberInput = Number(userInput);

try {
if (/\d{5,}/.test(userInput)) { //1451001600000
let msDate = new Date(numberInput);
let humanDate = msDate.toUTCString();
res.json({“unix”: Date.parse(humanDate),
“utc”: humanDate});
}
res.json({“unix”: Date.parse(userInput),
“utc”: userDay.toUTCString()});
}catch(err) {
console.log(err);
res.json({“error”: ‘Invalid Date’});
}

});

I solved!
Put my code here for someone with the same issue later.

app.get("/api/:date", function (req, res) {
let userInput = req.params.date;
let userDay = new Date(userInput);
let numberInput = Number(userInput);
let msDate = new Date(numberInput);
let humanDate = msDate.toUTCString();

if (Date.parse(userInput) || humanDate != 'Invalid Date'){
    if (/\d{5,}/.test(userInput)) { //1451001600000
      res.json({"unix": Date.parse(humanDate), 
              "utc": humanDate});  
    }else {
      res.json({"unix": Date.parse(userInput),
              "utc": userDay.toUTCString()});
    };
    
  }
  res.json({"error": 'Invalid Date'})

});

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.