Timestamp: API and Microservices

Tell us what’s happening:
I got all the tests to work except for the ‘error’ one.
This is my thoughts:

  1. get input of user
  2. define valid date string (new Date(<user’s input>))
  3. if date string is valid and is 1479663089000, return correct json
  4. if date string is valid and is “2016-11-20”, return correct json
  5. if date string is invalid, return error in json

Am I wrong in my logic?

Your code so far

// no parameters
app.get(‘/api/timestamp/’, (req, res) => {
res.json({
‘unix’: new Date().getTime(),
‘utc’: new Date().toUTCString()
});
})

// with parameters
app.get(‘/api/timestamp/:date_string?’, (req, res) => {

const {date_string} = req.params; // user’s input

// make valid date
let date = new Date(date_string);
// console.log(date: ${date}, date_string: ${date_string})

// if date is valid
// user input is 1479663089000
if (typeof(parseInt(date_string === ‘Number’)) && date.toString().length <= 16) {
res.json({
unix: new Date(parseInt(date_string)).getTime(),
utc: new Date(parseInt(date_string)).toUTCString()
})
}

// user input is 2016-11-20
if (date) {
res.json({
unix: new Date(date).getTime(),
utc: new Date(date).toUTCString()
})
}

// if date is not valid
if (!date) {
res.json({
“error” : “Invalid Date”
})
}
})

Your browser information:

User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/85.0.4183.102 Safari/537.36.

Challenge: Timestamp Microservice

Link to the challenge:

This is how you should check for an Invalid Date:

if(date.toString() === "Invalid Date" ) { res.json({error: "Invalid Date"}); } else { // Display the UTC and Unix timestamps }

Hey Herman,
Thanks for the solution.
Now my Unix Valid date test is not working. Any idea why? It seems it equates to an invalid date…

app.get(‘/api/timestamp/:date_string?’, (req, res) => {

const {date_string} = req.params; // user’s input

// make valid date
let date = new Date(date_string);
// console.log(date: ${date}, date_string: ${date_string})

// if date is not valid
if (date.toString() === ‘Invalid Date’) {
res.json({
“error” : “Invalid Date”
})
}

// if date is valid
// user input is 1479663089000
if (typeof(parseInt(date_string === ‘Number’)) && date.toString().length <= 16) {
res.json({
unix: new Date(parseInt(date_string)).getTime(),
utc: new Date(parseInt(date_string)).toUTCString()
})
}

if (date) {
// user input is 2016-11-20
res.json({
unix: new Date(date).getTime(),
utc: new Date(date).toUTCString()
})
}
})

Well, i think a Unix time stamp is simply a number which indicates the no of seconds from 1970-01-01 , and you should test if the first 5 digits are numbers.

something like

// if date is valid
// user input is 1479663089000
if(/\d{5,}/.test(date_string)){
   res.json({ unix: date_string,  utc: new Date(parseInt(date_string).toUTCString())})