Timestamp Microservice: Empty Date Parameter Issue

I’m currently working on the FreeCodeCamp Timestamp Microservice project and I’ve encountered an issue with the implementation. While most of the requirements pass successfully, I’m having trouble with the test case for handling an empty date parameter. Here are the specifics:

Passed Tests:

  • A request to /api/:date? with a valid date returns a JSON object with unix and utc keys.
  • A request to /api/1451001600000 returns the correct timestamp.
  • The project can handle dates parsed by new Date(date_string).
  • Invalid date strings return { error: “Invalid Date” }.

Failed Tests:

  • An empty date parameter should return the current time in a JSON object with a unix key.
  • An empty date parameter should return the current time in a JSON object with a utc key. Here’s the code I’m using:
// index.js
// where your node app starts

// init project
var express = require('express');
var app = express();
dotenv = require('dotenv');
dotenv.config();

// enable CORS (https://en.wikipedia.org/wiki/Cross-origin_resource_sharing)
// so that your API is remotely testable by FCC 
var cors = require('cors');
app.use(cors({ optionsSuccessStatus: 200 }));  // some legacy browsers choke on 204

// http://expressjs.com/en/starter/static-files.html
app.use(express.static('public'));

// http://expressjs.com/en/starter/basic-routing.html
app.get("/", function (req, res) {
  res.sendFile(__dirname + '/views/index.html');
});

const isInvalidDate = (date) => date.toUTCString() === "Invalid Date"

// your first API endpoint... 
app.get("/api/:date", function (req, res) {
  let date = new Date(req.params.date)

  if (isInvalidDate(date)) {
    date = new Date(+req.params.date)
  }

  if (isInvalidDate(date)) {
    res.json({ error: "Invalid Date" })
    return;
  }

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

app.get("/api", (req, res) => {
  res.json({
    unix: new Date().getTime(),
    utc: new Date().toUTCString()
  })
})



// listen for requests :)
var listener = app.listen(process.env.PORT, function () {
  console.log('Your app is listening on port ' + listener.address().port);
});

I expected that when making a request to /api/ or /api, the server would return the current time in both Unix and UTC formats as a JSON object.

Hello and welcome to the forum;
If you move your topic to Backend Development` section you can take more quick response.

Edit: If you can’t doesn’t matter. Did you try declare a new variable for Date object?

1 Like

Your code is passing for me.

Make sure your system clock is correct (force a sync of the time).

1 Like

Thank you! It works now.