Timestamp, i'm going to do it

Hi everybody, i’m facing this challenge, i’ve copied your repository from github to start the project, and after in server.js, after the code that was just present, i add this code:

app.get("/api/2015-12-25", (req,res)=>{
   res.json({ unix: 1451001600000, utc: "Fri, 25 Dec 2015 00:00:00 GMT" })
app.get("/api/1451001600000", (req, res)=>{
  res.json({ unix: 1451001600000, utc: "Fri, 25 Dec 2015 00:00:00 GMT" })

app.get("/api/:date", (req,res)=>{
  const {date} = req.params
  const primoUnix = new Date({date})
  let unix = primoUnix.getTime()
  res.json(unix, {date})


with the first two api request there aren’t problem, but i need some hints on the last api request, for sure i’m wrong in something, i hope you can lead me to the solving. Thanks

That’s not a valid json response. And you should see it somewhere in the console that Express is not happy with the response.

As a personal note.

There is this principle when writing software called DRY (don’t repeat yourself).
You can see that all 3 endpoint so far take the same params, a :date and return the exact JSON response: {unix, utc}.

So everything could be, and should be, unified in a single handler.

Hope this helps. :sparkles:

Understood, i ‘‘repeat myself’’ because i’m a newbie, but you are totally right, i’m going to work on it! Thanks

Just in case I didn’t make myself clear in the response above, you should be able to quickly fix the JSON response, something like:

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

It won’t be enough to clear the challenge, but at least you will start getting responses. :slight_smile:

Hope this helps :sparkles:

I’ve passed!!! Here’s how i rewrote my code:

app.get('/api/:date?', (req, res) => {

    let date = new Date();

    if (req.params.date) {
        let unixDate = +req.params.date;

        date = isNaN(unixDate) ? new Date(req.params.date) : new Date(unixDate);

        if (!(date instanceof Date) || isNaN(date.getTime())) return res.json({ error: "Invalid Date" });

    return res.json({ unix: date.getTime(), utc: date.toUTCString() });

I’m so happy, THANK YOU for your hints!! :smiley: :smiley: :smiley:

1 Like