You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React中如何转换MongoDB/Mongoose返回的时间戳为指定日期格式

解决MongoDB/Mongoose日期字段在GraphQL中返回时间戳并格式化的问题

问题背景

你的Mongoose Schema中eventStartDate定义为Date类型,数据库存储为ISO格式(如2022-09-03T00:00:00.000+00:00),但GraphQL查询返回毫秒级时间戳,需要转换为MM/DD/YYYY格式(如09/03/2022)。

三种可行解决方案

1. 前端直接转换(推荐快速实现)

拿到GraphQL返回的时间戳后,用JavaScript编写格式化函数处理:

function formatMMDDYYYY(timestamp) {
  const date = new Date(timestamp);
  // 月份从0开始,需+1,padStart保证两位数字格式
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  const year = date.getFullYear();
  return `${month}/${day}/${year}`;
}

// 使用示例
const rawTimestamp = 1666396800000;
const formattedDate = formatMMDDYYYY(rawTimestamp); // 输出 "09/03/2022"

2. 在GraphQL Resolver中提前格式化

如果希望GraphQL直接返回格式化后的字符串,修改对应字段的Resolver:

// 示例Resolver片段
const resolvers = {
  Query: {
    getEvent: async (parent, args) => {
      const event = await Event.findById(args.id);
      return event;
    }
  },
  Event: {
    eventStartDate: (parent) => {
      const date = new Date(parent.eventStartDate);
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      const year = date.getFullYear();
      return `${month}/${day}/${year}`;
    }
  }
};

同时更新GraphQL类型定义,将eventStartDate的类型从Date改为String:

type Event {
  id: ID!
  eventStartDate: String!
  # 其他字段...
}

3. 配置Mongoose Schema自动格式化

通过Mongoose的get属性,让Schema在返回文档时自动转换日期格式:

// 修改你的Mongoose Schema
const eventSchema = new mongoose.Schema({
  eventStartDate: {
    type: Date,
    get: function(dateValue) {
      const date = new Date(dateValue);
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      const year = date.getFullYear();
      return `${month}/${day}/${year}`;
    }
  },
  // 其他字段...
});

// 确保getter在序列化时生效
eventSchema.set('toJSON', { getters: true });
eventSchema.set('toObject', { getters: true });

这种方式下,Mongoose从数据库取出数据后会自动转成格式化字符串,GraphQL直接返回该字符串即可(同样需要修改GraphQL类型为String)。

补充说明

GraphQL返回时间戳的原因是:Mongoose的Date对象在序列化为JSON时,默认会转换为毫秒级时间戳。通过上述任意一种方式,都可以将其转换为你需要的MM/DD/YYYY格式。

内容的提问来源于stack exchange,提问作者Stephen Scott Moore

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.17 19:05:46