Timestamp Microservice, one test hasn't been passed

Hi there!
All of my tests have been passed, except this one:

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

This is my code:

app.get('/api/:date?', function (req, res) {
    let dateParam = req.params.date;

    if (! dateParam) {
        res.json({
            unix: new Date().getTime(),
            utc: new Date().toUTCString()
        })
    }

    if (! dateParam.includes('-')) {
        dateParam = +dateParam;
    }

    if (isNaN(new Date(dateParam).getSeconds())) {
        res.json({ error : "Invalid Date" })
    }

    res.json({
        unix: new Date(dateParam).getTime(),
        utc: new Date(dateParam).toUTCString()
    });
});

What’s going wrong?

Challenge: Timestamp Microservice

Link to the challenge:

Not sure, but I think negative numbers are valid input to the Date constructor. So, new Date(-1) would evaluate to one millisecond before 1970-01-01. Anyway, with your program an input of “-1” would not be converted to a number, and so would be evaluated as a string, giving you an invalid date.

1 Like

It’s definitely the handling of a parseable date string problem. This

seems to be looking for a dash in a date string on the assumption that they will all be like 2011-10-05 when the test actually uses 05 October 2011 as the test value, which will get matched as invalid by this code.

1 Like

Thank you. I changed that to this:

if (! Number.isNaN(Number(dateParam))) {
        dateParam = Number(dateParam);
}

But it doesn’t pass the same test. I tested it with 05 October 2011 and the output is:

{
   "unix": 1317760200000,
   "utc": "Tue, 04 Oct 2011 20:30:00 GMT"
}

What’s the problem guys?

Hello there,

Would you mind linking to your app?

1 Like

That wasn’t necessarily the only problem; just the one I spotted first. As always, the easiest way to debug is to log your route inputs with console.log(dataParam); and your route responses right before your response, everywhere there is a response. Then run the tests against your project and look at the logs.

Two other things: first, you need to return at responses, like return res.json(...);. This code will send multiple responses if the conditional matches.

Second, new Date(...) will return Invalid Date on invalid dates.

1 Like

Sure.

I’m really confused.

It looks like your current code passes the tests.

1 Like

Your code/app also passes the tests for me. Have you fixed your issue?

1 Like

Hooray! I didn’t change my code! I just took a rest and opened it again, and now I find it passes the tests! I don’t know what’s happened! :grinning_face_with_smiling_eyes:

Thanks guys

1 Like

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