Express: how to format Date in json response?

Created on 4 Nov 2015  路  2Comments  路  Source: expressjs/express

how to format Date in json response?

now, detault like this: createTime: "2015-11-03T09:05:33.026Z"

4.x question

Most helpful comment

Hi! So assuming you are using res.json (http://expressjs.com/4x/api.html#res.json), then it's important to note that all we do is the standard JSON.stringify operation (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify) on the argument, and the second argument for that you can define as the json replacer setting (http://expressjs.com/4x/api.html#app.set). So, if you wanted to stringify Date objects differently, for example, here is a way you can define this on your app:

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

  return value;
});

All 2 comments

Hi! So assuming you are using res.json (http://expressjs.com/4x/api.html#res.json), then it's important to note that all we do is the standard JSON.stringify operation (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify) on the argument, and the second argument for that you can define as the json replacer setting (http://expressjs.com/4x/api.html#app.set). So, if you wanted to stringify Date objects differently, for example, here is a way you can define this on your app:

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

  return value;
});

3Q

Was this page helpful?
0 / 5 - 0 ratings

Related issues

HafidAbnaou picture HafidAbnaou  路  3Comments

cuni0716 picture cuni0716  路  3Comments

afanasy picture afanasy  路  3Comments

gaurav5430 picture gaurav5430  路  3Comments

extensionsapp picture extensionsapp  路  3Comments