Timestamp Microservice - Can someone explain how I get my app to send an error if the date is inputted in the wrong format?

// server.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({optionSuccessStatus: 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'});
});




app.get("/api/timestamp/:dateVal", function(req,res,next){

var dateVal = req.params.dateVal;

  
var dateFormatingOptions = {
year:'numeric',
month:'long',
day:'numeric',
time: 'numeric'   
};
  
  
if(isNaN(dateVal)){
var naturalDate = new Date(dateVal)
naturalDate = naturalDate.toUTCString("en-uk", dateFormatingOptions)
var unixDate = new Date(dateVal).getTime();
}



res.json({unix: unixDate, utc: naturalDate})
});



// listen for requests :)


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

hi,
you could do something like this:

res.json(dateInCorrectFormat ?
              {unix: unixDate, utc: naturalDate} :
              {"error" : "Invalid Date"})

Or are you having trouble how to determine if date is in correct format?

This code seems to give me an error. It keeps saying that there’s an unexpected token.

Did you replaced placeholder dateInCorrectFormat with code?
Are you building you project on Glitch? If so - you could share the link so it would be easier to debug :slight_smile:

Do you mean a placeholder for the date?

Cannot open your link for some reason… (glitch returns: “We didn’t find trite-dahlia”).

condition ? exprIfTrue : exprIfFalse 

By placeholder I mean that dateInCorrectFormat is not a built in Javascript function. You need to replace dateInCorrectFormat with some condition that checks if date is in correct format.

Hint: when date is not valid - new Date() returns “Invalid Date” .

All solved now! Thanks

1 Like