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

如何从MongoDB存储的日期中提取年月并在React组件中使用?

问题解答:在React组件中格式化MongoDB返回的ISODate日期

你当前代码里直接用listing.dateofbirth.year会报错,因为后端接口返回的dateofbirth是字符串格式的ISODate(比如"1990-05-15T00:00:00.000Z"),不是JavaScript的Date实例,所以没有.year这个属性。要提取年份或月份,需要先把字符串转成Date对象,再调用对应的方法。

解决方法

1. 直接在组件中转换并提取

在渲染列表时,把日期字符串转成Date对象,然后用getFullYear()(获取4位数年份)、getMonth()(获取月份,注意返回值是0-11,需要加1得到1-12的月份)等方法提取所需部分:

修改你的React组件渲染部分:

{userListings && userListings.length > 0 && userListings.map((listing)=> {
  // 把字符串转成Date对象
  const birthDate = new Date(listing.dateofbirth);
  const passingDate = new Date(listing.dateofpassing);
  
  return (
    <div key={listing._id}>
        <Link>
        <div>
            <img src={listing.imageUrl} alt="Person image" />
            <div>
                <h1>{listing.givenname + ' ' + listing.familyname}</h1>
                {/* 提取年份 */}
                <p>{birthDate.getFullYear()} - {passingDate.getFullYear()}</p>
                {/* 如果要显示月份+年份,比如 05/1990 - 03/2024 */}
                {/* <p>{(birthDate.getMonth()+1).toString().padStart(2, '0')}/{birthDate.getFullYear()} - {(passingDate.getMonth()+1).toString().padStart(2, '0')}/{passingDate.getFullYear()}</p> */}
            </div>
        </div>
        </Link>
    </div>
  )
})}

2. 封装工具函数复用

如果多个组件都需要处理日期格式,可以封装一个工具函数,避免重复代码:

// 工具函数:从日期字符串中提取年份
const extractYear = (dateStr) => {
  if (!dateStr) return '';
  const date = new Date(dateStr);
  // 检查日期是否有效
  if (isNaN(date.getTime())) return '无效日期';
  return date.getFullYear();
};

// 工具函数:从日期字符串中提取月份(1-12)
const extractMonth = (dateStr) => {
  if (!dateStr) return '';
  const date = new Date(dateStr);
  if (isNaN(date.getTime())) return '无效日期';
  return date.getMonth() + 1;
};

然后在组件中使用:

<p>{extractYear(listing.dateofbirth)} - {extractYear(listing.dateofpassing)}</p>

额外说明

  • 为什么不用.year?:JavaScript的Date对象没有.year属性,正确获取年份的方法是getFullYear(),getYear()是废弃方法,不要使用。
  • 日期有效性:建议加上isNaN(date.getTime())判断,避免无效日期字符串导致的报错。

内容的提问来源于stack exchange,提问作者thinkerSajjad

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.03 21:17:26