Timestamp Microservice

I do not understand the reason why this is not working

// index.js
// where your node app starts

// init project
var express = require("express");
var app = express();

// 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");
});

// your first API endpoint...
app.get("/api/", function (req, res) {
  let date = new Date(); //This method returns the current date and time, as a string.
  let utcDate = date.toUTCString(); //it transforms the date object into an UTC
  let unixDate = date.getTime(); //

  //console.log("unixDate: ", unixDate, "utc: ", utcDate);
  res.json({ unix: unixDate, utc: utcDate });
});

app.get("/api/hello", function (req, res) {
  res.json({ greeting: "hello API" });
});

app.get("/api/:date", function (req, res) {
  let date = req.params.date; //get the client's info

  //console.log(typeof date);
  if (/^\d{4}\-\d{2}\-\d{2}$/.test(date)) {
    let dateInUnix = new Date(date).getTime();
    let objDate = new Date(parseInt(dateInUnix)); //it transforms the client' input into a date object

    let utcDate = objDate.toUTCString(); //it transforms the date object into an UTC
    //console.log(typeof dateInUnix, typeof utcDate);
    res.json({ unix: dateInUnix, utc: utcDate }); //The api sends the requested response by the client
  } else if (/^\d+$/.test(date)) {
    let unixDateInNumber = parseInt(date);
    let objDate = new Date(parseInt(date)); //it transforms the client' input into a date object
    let utcDate = objDate.toUTCString(); //it transforms the date object into an UTC
    //console.log("unix", objDate, "utcDate", utcDate);
    //console.log(typeof unixDateInNumber, typeof utcDate);
    res.json({ unix: unixDateInNumber, utc: utcDate }); //The api sends the requested response by the client
  } else {
    res.json({ error: "Invalid Date" });
  }
});

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

You need to be able to handle this request

http://localhost:3000/api/05%20October%202011,%20GMT

So the date param would be 05 October 2011, GMT

1 Like

It does not work yet.

// index.js
// where your node app starts

// init project
var express = require("express");
var app = express();

// 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");
});

// your first API endpoint...
app.get("/api/hello", function (req, res) {
  res.json({ greeting: "hello API" });
});

// Date microservice starts here
app.get("/api/:date?",(req,res) => {

  const dateStr = req.params.date;

  /* If no date parameter is present then respond with current date in both formats */
  if (!dateStr){
    let date = new Date();
    return res.json({unix: date.getTime(), utc: date.toUTCString()});
    }
  if (isNaN(dateStr)){
  /* Date parameter IS NOT a number */
    let dateObj = new Date(dateStr);
    if (dateObj.toString() === 'Invalid Date'){
      return res.json({error: "Invalid Date"});
    }else {
      return res.json({unix: dateObj.getTime(), utc: dateObj.toUTCString()});
    }
  } 
  /* Date parameter IS a number*/
  let dateObj = new Date(parseInt(dateStr));
  if (dateObj.toUTCString() === 'Invalid Date'){
    return res.json({error: "Invalid Date"});
  } else {
      return res.json({unix: dateStr, utc: dateObj.toUTCString()});
  }
});

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

Your unix value is type string, it should be type number.

http://localhost:3000/api/1451001600000

Your response:

{"unix":"1451001600000","utc":"Fri, 25 Dec 2015 00:00:00 GMT"}
1 Like
// index.js
// where your node app starts

// init project
var express = require("express");
var app = express();

// 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");
});

// your first API endpoint...
app.get("/api/", function (req, res) {
  let date = new Date(); 
  let utcDate = date.toUTCString(); 
  let unixDate = date.getTime(); //
}


app.get("/api/hello", function (req, res) {
 
  res.json({ greeting: "hello API" });
});

app.get("/api/:date?", function (req, res) {
  let date = req.params.date;
  let dateToConvert = new Date(date);


  if (dateToConvert != "Invalid Date") {
    if (dateToConvert.toUTCString() !== "Invalid Date") {
      let unix = Date.parse(dateToConvert);
      var unixTimestamp = Math.floor(unix / 1000);
      let utcString = dateToConvert.toUTCString();
      res.json({ unix: unixTimestamp, utc: utcString });
    }
  } else if (/[0-9]*/.test(date)) {
    let unix = parseInt(date);
    let utcString = new Date(unix).toUTCString();
    console.log(typeof unix, typeof utcString);
    res.json({ unix: unix, utc: utcString });
  } else {
    res.json({ error: "Invalid Date" });
  }
});

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

It does not work yet.

You have syntax errors and your code is more wrong now than before.

The second code you posted would pass if you just converted the unix value to a number in the response.

1 Like

It still does not work. I changed the code a little bit.

app.get("/api/", function (req, res) {
  let date = new Date();
  let utcDate = date.toUTCString();
  let unixDate = date.getTime(); //*/
    //console.log("unix: ", unixDate,"utc: ",utcDate);
  console.log(typeof unixDate, typeof utcDate)
  res.json({ unix: unixDate, utc: utcDate });
});

app.get("/api/:date?", function (req, res) {
  let date = req.params.date;
  let dateToConvert = new Date(date);

  
  if (dateToConvert == "Invalid Date") {
        if(/[0-9]/.test(date)){
            let parsIntDate =parseInt(date);
            let unixDateToConvert = new Date (parsIntDate);
            let utcTimestamp =  unixDateToConvert.toUTCString();
            res.json({unix: parsIntDate, utc: utcTimestamp});
            console.log("unixTimeStamp", parsIntDate,"unixDateToConvert: ",unixDateToConvert,"utcTimestamp: ", utcTimestamp);
            console.log(typeof parsIntDate, typeof utcTimestamp)
        }else{
            res.json({error : "Invalid Date"});
        }
      

}else{
        let dateInMilliseconds = dateToConvert.getTime()
        let unixTimestamp = Math.floor(dateInMilliseconds);
        let unixDateToConvert = new Date (unixTimestamp);
        let utcTimestamp =  unixDateToConvert.toUTCString();
    //console.log("unixTimestamp: ", unixTimestamp, "utcTimestamp: ",utcTimestamp)
        console.log(typeof unixTimestamp , typeof utcTimestamp)
            res.json({unix: unixTimestamp, utc: utcTimestamp})
            }

I don´t understand it. How does FCC test the program? I do the test by myself and it is correct.

Please do not post incomplete code. It makes it much harder to test it.

As I said, the second code you posted will pass if you make sure the unix property value is a number. In the last res.json() call dateObj.getTime() like you are in all the other responses you have.

The tests:

https://github.com/freeCodeCamp/freeCodeCamp/blob/main/curriculum/challenges/english/05-back-end-development-and-apis/back-end-development-and-apis-projects/timestamp-microservice.md


Code comment on last res
// index.js
// where your node app starts

// init project
var express = require("express");
var app = express();

// 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");
});

// your first API endpoint...
app.get("/api/hello", function (req, res) {
  res.json({ greeting: "hello API" });
});

// Date microservice starts here
app.get("/api/:date?",(req,res) => {

  const dateStr = req.params.date;

  /* If no date parameter is present then respond with current date in both formats */
  if (!dateStr){
    let date = new Date();
    return res.json({unix: date.getTime(), utc: date.toUTCString()});
    }
  if (isNaN(dateStr)){
  /* Date parameter IS NOT a number */
    let dateObj = new Date(dateStr);
    if (dateObj.toString() === 'Invalid Date'){
      return res.json({error: "Invalid Date"});
    }else {
      return res.json({unix: dateObj.getTime(), utc: dateObj.toUTCString()});
    }
  } 
  /* Date parameter IS a number*/
  let dateObj = new Date(parseInt(dateStr));
  if (dateObj.toUTCString() === 'Invalid Date'){
    return res.json({error: "Invalid Date"});
  } else {
      // use dateObj.getTime() for the unix value
      return res.json({unix: dateStr, utc: dateObj.toUTCString()});
  }
});

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

Does this code pass on your computer?

// index.js
// where your node app starts

// init project
var express = require("express");
var app = express();

// 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");
});

// your first API endpoint...
app.get("/api/hello", function (req, res) {
  res.json({ greeting: "hello API" });
});

// Date microservice starts here
app.get("/api/:date?", (req, res) => {
  const dateStr = req.params.date;

  /* If no date parameter is present then respond with current date in both formats */
  if (!dateStr) {
    let date = new Date();
    return res.json({ unix: date.getTime(), utc: date.toUTCString() });
  }
  if (isNaN(dateStr)) {
    /* Date parameter IS NOT a number */
    let dateObj = new Date(dateStr);
    if (dateObj.toString() === "Invalid Date") {
      return res.json({ error: "Invalid Date" });
    } else {
      return res.json({ unix: dateObj.getTime(), utc: dateObj.toUTCString() });
    }
  }
  /* Date parameter IS a number*/
  let dateObj = new Date(parseInt(dateStr));
  if (dateObj.toUTCString() === "Invalid Date") {
    return res.json({ error: "Invalid Date" });
  } else {
    // console.log("dateObj: ", dateObj, "dateStr :", dateStr);
    //console.log("This is the correct one");

    let unix = parseInt(dateStr);
    let unixTimestamp = Math.floor(unix) * 1000;
    let utcString = new Date(unixTimestamp).toUTCString();
    // console.log("unix:", unixTimestamp, "utc: ", utcString);
    //console.log(typeof unix, typeof utcString);
    return res.json({ unix: unixTimestamp, utc: utcString });
  }
});

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

No, it doesn’t, because it isn’t the correct response value.

A request to /api/1451001600000 should return { unix: 1451001600000, utc: "Fri, 25 Dec 2015 00:00:00 GMT" }

Your response:

{"unix":1451001600000000,"utc":"Wed, 31 May 47950 00:00:00 GMT"}

Use the browser dev tools and inspect the request/response in the network tab when you submit the code.


Why are you refusing to do what I said to do?

1 Like

I have changed the code as you proposed. I am sorry for ignoring your suggestion. I just wanted to try something different… I set res.json{(unix: dateObj.getTime(), utc: dateObj.toUTCString() }) as you told me.

Though the changes, I still cannot pass the tests.

// index.js
// where your node app starts

// init project
var express = require("express");
var app = express();

// 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");
});

// your first API endpoint...
app.get("/api/hello", function (req, res) {
  res.json({ greeting: "hello API" });
});

// Date microservice starts here
app.get("/api/:date?", (req, res) => {
  const dateStr = req.params.date;

  /* If no date parameter is present then respond with current date in both formats */
  if (!dateStr) {
    let date = new Date();
    return res.json({ unix: date.getTime(), utc: date.toUTCString() });
  }
  if (isNaN(dateStr)) {
    /* Date parameter IS NOT a number */
    let dateObj = new Date(dateStr);
    if (dateObj.toString() === "Invalid Date") {
      return res.json({ error: "Invalid Date" });
    } else {
      return res.json({ unix: dateObj.getTime(), utc: dateObj.toUTCString() });
    }
  }
  /* Date parameter IS a number*/
  let dateObj = new Date(parseInt(dateStr));
  if (dateObj.toUTCString() === "Invalid Date") {
    return res.json({ error: "Invalid Date" });
  } else {
    return res.json({ unix: dateObj.getTime(), utc: dateObj.toUTCString() });
  }
});

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

Thanks for your support during my learning jouney. I appreciate it really.

You marked this thread as solved so I assume you passed the tests?

1 Like

Yes, thank you very much for your help and guidance on this exercise. I appreciate it really.

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