简体   繁体   中英

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:

table.datatable
            thead
                tr
                    th ID
                    th Distance
                    th Last Seen
            tbody
                each item, i in uplinkjson.hubs[t].nodes
                    tr 
                        td= item.id
                        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();
//ok
/* 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') }

Output:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM