简体   繁体   English

在Jade和node.js中格式化(JSON)UNIX时间戳

[英]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: 我从JSON文件中获取数据,其中一个元素是时间戳记(last_seen),该时间戳记返回如下整数:

"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. 现在,我正在使用Jade&node.js创建一个表(利用jQuery插件DataTables),该表具有此元素的列。 I would like for each row to display the according dates and times for the integers being grabbed from the JSON. 我希望每一行显示从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. 我是JavaScript和Jade的新手。 My JS file looks like this: 我的JS文件如下所示:

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 . 如果您想更好地控制外观,可以使用诸如moment的库。 If you pass an instance of that module to res.render() , you can do the formatting directly in Jade: 如果您将该模块的实例传递给res.render() ,则可以直接在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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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