Human Cyborg Relations Human Cyborg Relations - 28 days ago 6
Node.js Question

Timestamp microservice returning the wrong time (Node, Express, Moment)

I'm creating a timestamp microservice that follows these rules:

1) I can pass a string as a parameter, and it will check to see whether that string contains either a unix timestamp or a natural language date (example: January 1, 2016)

2) If it does, it returns both the Unix timestamp and the natural
language form of that date.

3) If it does not contain a date or Unix timestamp, it returns null
for those properties.

It works when I pass in a date in the MMMM DD, YYYY format, but if I pass in the unix time, I get some completely bogus values.

var express = require("express");
var app = express();
var port = process.env.PORT || 3000;
var moment = require("moment");

app.listen(port, function(){
console.log("Listening on port " + port);

app.get("/", function(req, res){
res.writeHead(200, {"Content-Type": "text/html"});
res.end("Hi! This is a timestamp microservice. <a href=''>See instructions here.</a>");

app.get("/:date", function(req, res){
var newDate =;

var natural = moment(newDate, "MMMM D, YYYY");
var unix = moment(newDate, "X");


if (natural.isValid() || unix.isValid()) {
if (natural.isValid()) {
newDate = natural;
} else {
newDate = unix;

res.json({unix: newDate.format("X"), natural: newDate.format("MMMM D, YYYY")});
} else {
res.json({unix: null, natural: null});


Oh and please let me know if I'm not using the correct style, or using any bad practices; I'm new to all this


According to the moment's documentation:

The parser ignores non-alphanumeric characters, so both of the following will return the same thing [...]

So, a unix timestamp like '1475190112' will actually make natural.isValid() === true, and that's where everything goes wrong.

Luckily, the docs also say:

As of version 2.3.0, you may specify a boolean for the last argument to make Moment use strict parsing. Strict parsing requires that the format and input match exactly, including delimeters.

So, if you parse your dates like this:

var natural = moment(newDate, "MMMM D, YYYY", true);
var unix = moment(newDate, "X", true);

Then natural.isValid() will correctly return false and everything will work as expected.