DEV Community

Thu Htet Tun
Thu Htet Tun

Posted on

Freecodecamp Backend Development & APIs (Timestamp Task My Answer)

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

let unixTimeStamp, utc;

if(new Date(date) == 'Invalid Date')
{
if( (new Date(parseInt(date))).getTime() == parseInt(date))
{
unixTimeStamp = parseInt(date);
utc = new Date(parseInt(date)).toGMTString()
return res.json({unix:unixTimeStamp,utc:utc});
}
}

if(date === undefined){
unixTimeStamp = new Date().getTime()
utc = new Date().toGMTString()
}else{
unixTimeStamp = new Date(date).valueOf()
utc = new Date(date).toGMTString()
}

if(isNaN(unixTimeStamp) && utc === 'Invalid Date')
{
return res.json({ error : "Invalid Date"});
}

return res.json({unix:unixTimeStamp,utc:utc});
});`

Top comments (0)