Junyu Wu
Junyu Wu

Reputation: 379

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}

Upvotes: 9

Views: 12572

Answers (4)

Shuvro
Shuvro

Reputation: 242

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

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

Upvotes: 0

Ronald Coarite
Ronald Coarite

Reputation: 4736

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;

});

Upvotes: 5

Victor Axelsson
Victor Axelsson

Reputation: 1466

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
}

Upvotes: 0

swapnesh
swapnesh

Reputation: 26732

You need to use Date.now()

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

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

Upvotes: 9

Related Questions