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

React中如何格式化NASA接口返回的日期以在Ant Design表格正常显示

Fixing Extra Characters in the Year Column of Your Ant Design Table (NASA Data)

Hey there! Let's tackle that formatting issue with the Year column in your Ant Design Table when using data from NASA's meteorite dataset. From what you described, the year field is coming back as a full ISO timestamp (like 2013-01-01T00:00:00.000) instead of just the clean 4-digit year, right? Here are a few solid, practical solutions to fix this:

Solution 1: Format the Data Before Passing to the Table

When you get the response from Axios, transform each item's year field to extract just the year part upfront. This way, your ResultTable receives pre-cleaned data and doesn't have to handle formatting logic.

// Inside your Axios request handler
axios.get(formQuery)
  .then(res => {
    const cleanedData = res.data.map(meteorite => ({
      ...meteorite,
      // Grab the first 4 characters from the ISO string (safe for valid dates)
      year: meteorite.year?.slice(0, 4) || 'N/A'
      // For safer edge case handling, use a Date object instead:
      // year: meteorite.year ? new Date(meteorite.year).getFullYear().toString() : 'N/A'
    }));
    this.setState({ searchResult: cleanedData });
  })
  .catch(err => console.error('Fetch error:', err));

Solution 2: Use Ant Design Table's render Prop

If you want to keep the original year timestamp intact (maybe for other uses later), you can format it directly in the column configuration. This keeps your raw data untouched but displays it cleanly in the table.

// Inside your ResultTable component's columns setup
const columns = [
  {
    title: 'Year',
    dataIndex: 'year',
    key: 'year',
    render: (yearValue) => {
      if (!yearValue) return 'N/A';
      // Quick slice for valid ISO dates
      return yearValue.slice(0, 4);
      // Or use Date parsing for inconsistent date formats:
      // return new Date(yearValue).getFullYear().toString();
    }
  },
  // Add your other columns here...
];

// Render the table as usual
<Table dataSource={searchResult} columns={columns} />

Solution 3: Optimize Your API Query to Get Only the Year

Since NASA's dataset uses the SODA API, you can modify your query to ask for just the year directly. This reduces the amount of data you fetch and eliminates the need for any client-side formatting entirely!

Update your formQuery to use $select and extract the year with SQL-like syntax:

// Build the query to fetch only the fields you need, plus the extracted year
let formQuery = `https://data.nasa.gov/resource/gh4g-9sfh.json?$select=name, id, EXTRACT(YEAR FROM year) AS year, mass, fall&$where=UPPER(name)like'${this.convertUserInputToQuery()}'`;

Make sure to replace the example fields (like mass, fall) with the actual columns your table requires. The API will return a numeric year value (e.g., 2013) directly, so your table can display it as-is!

Which Solution Should You Pick?

  • Go with Solution 1 if you want standardized, clean data across your app and don't need the full timestamp.
  • Use Solution 2 if you need to preserve the original date value for other features.
  • Choose Solution 3 for the most efficient approach—less data transfer and zero client-side processing.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.14 08:58:05