I have made a small timestamp microservice that converts from UNIX time to a natural language date, and vice versa. Please let me know of anything I could do better.
Here is a demo. Here is the time.js file that holds the class that controls converting the time:
let debug = require('debug')('test');
let moment = require('moment');
class TimeConverter {
constructor(){
this.naturalDate = null;
this.unixTime = null;
}
//check if string meets a specific format
checkString(string){
let format = /\w{3,9}?\s\d{1,2}?,\s\d{4}?/;
let unixFormat = /^\d[0-9]{0,20}$/;
let test = format.test(string);
let test2 = unixFormat.test(string);
if (test === true){
this.natToUnix(string);
} else if (test2 === true) {
this.unixToNat(string);
} else {
this.naturalDate = null;
this.unixTime = null;
}
return this.getResults();
}
//convert natural language date to unix
natToUnix(string){
//put into iso format for moment.js
let newDate = new Date(string);
//change into unix time
let date = moment(newDate).unix();
this.unixTime = date;
this.naturalDate = string;
}
//change unix time to natural language date
unixToNat(string){
let date = moment.unix(string);
let formatted = date.format("MMMM DD YYYY");
this.unixTime = string;
this.naturalDate = formatted;
}
getResults(){
let results = {unix: this.unixTime, natural: this.naturalDate};
debug(results);
return results;
}
}
let time = new TimeConverter();
module.exports = time;
Here is the server.js file that has some express code. It handles the routes in the application. It grabs the input from the request parameters, and serves the CSS / index.html files:
let express = require('express');
let debug = require('debug')('test');
let app = express();
let bodyParser = require('body-parser');
let time = require('./time.js');
let port = process.env.PORT || 8080;
app.use(bodyParser.json());
//serves static files
app.use('/static', express.static('public'));
app.use(bodyParser.urlencoded({ extended: true}));
//route for inputting the time
app.get(['/:time','/'], function(req,res){
res.sendFile(__dirname + "/index.html");
let data = req.params;
if (data.time != undefined){
res.json(time.checkString(data.time));
}
});
//tell server to listen on a port
app.listen(port, function(){
debug("listening on " + port);
});
Here is the repo.