Brandon Brandon - 4 months ago 20x
Node.js Question

Formatting a (JSON) UNIX timestamp in Jade & node.js

I'm getting data from a JSON file, of which one of the elements is a timestamp (last_seen) which returns integers like this:

"id": 4294901761,
"distance": 45,
"last_seen": 1465397445

Right now I'm using Jade & node.js to create a table (utilizing the jQuery plug-in DataTables) which has a column for this element. I would like for each row to display the according dates and times for the integers being grabbed from the JSON. My table gets generated in the following way:

th ID
th Distance
th Last Seen
each item, i in uplinkjson.hubs[t].nodes
td= item.distancejson
td= item.last_seen

I'm new to both JavaScript & Jade. My JS file looks like this:

var express = require('express');
var router = express.Router();
/* GET home page. */
router.get('/', function(req, res, next) {
var json = req.uplinkjson;
res.render('uplink', { 'uplinkjson': json});

module.exports = router;

Any guidance would be appreciated, thanks!


You can use something like this:

td #{ new Date(1000 * item.last_seen) }

Which would render this (for my timezone):

<td>Wed Jun 08 2016 16:50:45 GMT+0200 (CEST)</td>

If you want more control over how it looks, you can use a library like moment. If you pass an instance of that module to res.render(), you can do the formatting directly in Jade:

var json = req.uplinkjson;
res.render('uplink', {
  moment     : require('moment'),
  uplinkjson : json

And in your template:

td #{ moment(1000 * item.last_seen).format('YYYY/MM/DD, HH:MM') }


<td>2016/06/08, 16:06</td>