简体   繁体   中英

How to send timestamp in Express js json response?

res.json({data: new Date()});

This is the response: {data: '2014-05-20T01:40:34.993Z'}

How to configure express to return timestamp instead of date string?

{data: 1343235454545}

You need to use Date.now()

Example - res.json({data: Date.now()});

Then you will get result in timestamp "data": 1404359477253 likewise.

This worked out perfectly to filter all Date

app.set('json replacer', function (key, value) {
  if (this[key] instanceof Date) {
// Your own custom date serialization
value = this[key].now();
  }
  return value;

});

You can use moment.js (as suggested by @swapnesh). But I found it more suitable to simply save the data as a timestamp. Since I'm using mongoDB I'm using Number for the data type.

So my schema looks something like this:

var myDataSchema = {
    start: {type: Number, required: "myDataSchema.start is a required field"},
}

This will output:

{
    "_id": "564c6828d4f028236cf1a6c8",
    "start": ​1450969200
}

` Schema:({title:String},{timestamps:true})

`you can true the timestamps inside the model. I think problem solved

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