Timestamp Microservice

FreeCodeCamp Backend Challenge 1

The goal is to create a microservice that will take a date string or a unix timestamp and make a JSON response with both versions of the given timestamp / date.

Code

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
// timestamp.js
// Challenge 1 - Timestamp conversion UNIX <--> Standard

exports.convert = function (req, res) {
  var timestamp = req.params.timestamp
  var resData = {
    unix: null,
    natural: null
  }
  if (!timestamp) {
    res.json(resData)
  } else {
    const months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']
    if (isNaN(parseInt(timestamp))) {
      // is a string
      var date = new Date(timestamp)
      resData.natural = months[date.getUTCMonth()] + ' ' + date.getUTCDate() + ', ' + date.getUTCFullYear()
      resData.unix = Math.floor(date.getTime() / 1000)
    } else {
      // is a number (expect unix time)
      var unixDate = new Date(timestamp * 1000)
      resData.natural = months[unixDate.getUTCMonth()] + ' ' + unixDate.getUTCDate() + ', ' + unixDate.getUTCFullYear()
      resData.unix = timestamp
    }
    res.json(resData)
  }
}

Demo

View this code live on Heroku at fcc-challenges.herokuapp.com/…