To complete this project, knowledge of GET, JSON and Date object is necessary.
PART 1 Background
GET
This method requests a representation of specific source. It will only retrieve data. The query string (name/value pairs) is sent in the URL.
GET /genapp/customers?name=Joe%20Bloggs/
JSON (JS object notation)
As the name suggests, it is in the form of JS Object.
Date
Date
objects in JS contain a Number
that represents milliseconds since 1 January 1970 UTC. This date and time is the same as the UNIX epoch.
Coordinated Universal Time (UTC) is the global standard time defined by the World Time Standard. The number increases by exactly 86400 per day since the epoch.
Construct date objects
new Date() // the current date and time
new Date(value) // An integer value
new Date(dateString) // A string value representing a date, specified in a format recognized by the Date.parse()
method.
new Date(year, monthIndex [, day [, hours [, minutes [, seconds [, milliseconds]]]]]) // Individual date and time component values. Any missing fields are given the lowest possible value // month starts from 0. new Date(0, 0, 0, 0, 0, 0) Sun, 31 Dec 1899 00:00:00 GMT
let birthday = new Date(1995, 11, 17) // the month is 0-indexed
Static methods
Date.now()
Returns the numeric value corresponding to the current time.
Date.parse()
Parses a string representation of a date and returns UNIX epoch. Not recommended due to browser differences and inconsistencies.
Date.UTC()
Accepts the same parameters as the longest form of the constructor (i.e. year, monthIndex) and returns UNIX epoch.
Instance methods
Date.prototype.getDate() Date.prototype.getFullYear()
getMonth() getDay() getHours() getMinutes() getUTCDate() setDate() .... toString() // Wed Jul 28 1993 14:39:07 GMT+0200 (CEST) toDateString() //Wed Jul 28 1993 valueOf() // returns the primitive value
Part 2 The project
All right, now let’s look at how to complete this project!
The API endpoint is […]/api/timestamp/:date_string?
date_string is the parameter we’re going to look at. It is string type, to be clear.
There are two possible valid formats, one is “2016-11-20”, the other is unix epoch.
The latter needs to be converted from a string to a number.
We need to consider unhappy paths. If date_string is ‘fghjk’, then when we construct a new Date object, there is error, “Invalid Date”. So we need to handle this situation and return a warning.
Since this project is using Express.js framework, it becomes easier for us to call the API.
var app = express(); app.get(path, callback function);
The end.