Hej,
I dont understand the “Your project can handle dates that can be successfully parsed by `new Date(date_string)”-test in the API timestamp project. I pass every other test except this one and it feels very counter intuitive.
My Code:
const express = require('express');
var dayjs = require('dayjs')
//import dayjs from 'dayjs' // ES 2015
dayjs().format()
const app = express();
// enable CORS (https://en.wikipedia.org/wiki/Cross-origin_resource_sharing)
// so that your API is remotely testable by FCC
const 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');
});
app.get("/api/", (req, res) => {
res.json({ "unix": new Date().getTime(), "utc": new Date().getTime() })
})
app.get("/api/:date", (req, res) => {
const rawDate = req.params.date;
console.log(rawDate, new Date(rawDate))
if (dayjs(rawDate).isValid() && new Date(rawDate)) {
//create regexp-obj matching yyyy-mm-dd with date restrictions
const regexp_ymd = /^\d{4}\-(0?[1-9]|1[012])\-(0?[1-9]|[12][0-9]|3[01])$/;
if (regexp_ymd.test(rawDate)) {
const year = rawDate.slice(0, 4);
const month = rawDate.slice(5, 7);
const day = rawDate.slice(8);
const unix = Date.parse(rawDate);
const utc = new Date(Date.UTC(year, month - 1, day));
res.json({ unix: unix, utc: utc.toUTCString() });
} else if (Number(rawDate) >= 0) {
const utcMiliseconds = Number(rawDate / 1000);
const d = new Date(0); // declare date d at start of epoch time (1970)
d.setUTCSeconds(utcMiliseconds);
res.json({ unix: Number(rawDate), utc: d.toUTCString() });
}
else {
res.end();
}
} else {
res.json({ error: "Invalid Date" })
}
});
// listen for requests :)
const listener = app.listen(process.env.PORT, function() {
console.log('Your app is listening on port ' + listener.address().port);
});