将日期转换为字符串而不是 UTC 字符串

时间:2021-01-16 05:54:57

标签: node.js typescript express date timezone

我有一个 node + typescript 项目。并且正在执行以下操作:

export class Slot {
  startTime: Date;
  constructor(_startTime: Date){
   this.startTime = _startTime
 }
}
// In some controller method

const slot = new Slot(new Date()); // Here the date is in the System Timzone
// Some logic for the Date object before sending the response
response.json(slot);

现在,在响应中,startTime 没有保留系统 TZ,它被转换为 UTC。 要求在系统时区发送它。我可以手动执行 .toString() 这将使其进入系统时区但希望避免它,因为 Date 对象正在获取在响应中发送之前处理了很多地方。

1 个答案:

答案 0 :(得分:0)

您可以定义 json replacerJSON.stringify 使用的 replacer 参数)。

app.set('json replacer', function (key, value) {
  if (value instanceof Date) {
    // Apply required format
    return value.toLocaleString();
  }

  return value;
});